答: I would usually keep the collaborator objects as pointer members in the object that will use them. I would also usually have them implemented using an abstract class and pass the pointers as parameters to Shop's constructor rather than having Shop building them itself. This decouples Shop from the detail of how products are loaded, and means I can change to a different source of Products without needing to modify Shop; this is the fundamental essence of the Open/Closed principle, which some people describe as the most important principle on object-oriented design.</p>

Title: How do you decide member objects?

Body:
So OOP is about breaking down functionality, making each class responsible for one thing etc. But let's take the example where an object is using another object. First thing that comes to mind "composition, of course!".

I have 2 questions:

Question 1:
Suppose you have a Shop that is loading products from a file using a ProductsLoader, which in term uses a ProductsFileReader. You design the API so that the code is simple and readable and specialized. Therefore, you are able to do this:

```<code>    std::shared_ptr<Shop> shop = std::shared_ptr<Shop> (new Shop());
    shop->LoadProducts();
    // other code
</code>```

In LoadProducts you do this:

```<code>    m_productsLoader.LoadAllProducts();
    std::shared_ptr<Products> products = m_productsLoader.GetAllProducts();
    this->setProducts(products);
</code>```

In LoadAllProducts() you do this:

```<code>    prodFileReader.OpenProductsFile();
    prodFileReader.LoadDescriptionsFromFile();
    prodFileReader.CloseProductsFile();

    // create products from descriptions
    std::shared_ptr<Descriptions> descriptions = prodFileReader.GetProductsDescriptions();
    this->createProductsFromDescriptions(descriptions);
</code>```

And now here is the question: Do you keep ProductsLoader m_productsLoader as a Shop member? The same for ProductsFileReader: should it be a member of ProductsLoader? The alternative for this is creating these objects on the stack: when your functions are using one of them, you just declare, initialize etc them in the function and they get destructed when the function exits. Does this defy the purpose of OOP?

Question 2:
Let's say you decided to keep them as members. How do you know wheter you should keep the whole object as a member, or you should keep only a pointer to it (and, of course, in the constructor, instantiate the member and assign the pointer). Whether you access the member with the dot opperator . or arrow ->, it will perform the same functionality.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: Can you take this 10-page report that I asked you to prepare as a word document and make it into a powerpoint presentation because I am really a visual thinker and won't actually read the written report I asked you to make?</p>

ContentLicense: CC BY-SA 2.5


问:
How do you explain the source of an identifed problem without making it an "excuse"?
As practicing (as much as I can at least) "egoless programming", I'm focused on solving problems whoever wrote the code related (if that person don't make dangerous code) and I like to understand the problem fully to be sure to solve the source of this problem.

However, when someone point my code to show an error, I often try to remember what was my mindset while writing the defect code and I try to explain it to the guy pointing the error to make clear what was the error source (for example when some names are badly choosen, you might use them in a way they were not intended too and with apparent success...).

Now, I do this by reflex and most of my coworkers does understand this reflex. But I also worked in companies where coworkers were in a mentality of blaming the people that made the identified problems, with or without humour (for me it have the same not-sane effect anyway).

In this kind of environnement, explaining why you got to write wrong code makes others think that you're trying to build an excuse. I remarked that most non-technical people (or non domain-expert, not sure, it's only personal experience) also react exactly like that when you try to explain why you did something wrong.

So, when dealing with this kind of people/environnement, how do you manage to explain the real source of the error without looking like "making an excuse"? (and is it even worth trying to explain?)

答:
Take responsibility for it. Steven Covey phrases it as response-ability: your ability to respond. Say what you will do in the future to prevent doing something like that again, and follow through. Overall you should be concerned about your long-term reputation, and not the immediate moment.

If you own up to mistakes, people will appreciate it and respect you more. It will give you more credibility when something isn't an error (or at least not your own) and does need explanation.

Also, even if not delivered well, take it as constructive feedback and thank whoever pointed out the problem. If you are unsure what they say is wrong with your code, ask follow up questions.


问:
Creating a tree of objects based on the commonness of its properties?
I have an algorithm problem. I'll simplify the issue, because most of what I'm dealing with has nothing to do with the algorithm I need.

Basically, I have a list of objects that each have properties. Let's say for the sake of simplicity that this was a simple struct or another simple data type containing a string ID and an array of strings that are its properties. The properties can be things like "tool", "weapon", "food", etc.

What I need to do is turn this list of objects into a tree, where the most common properties go on top, and the least common go on the bottom. It's a bit more complex than that, actually. For example, let's say that I have:

Four objects with only the "weapon" property.

Six objects with a "tool" and "weapon" property.

Two items with a "food" and "fruit" property.

One item with a "tool" property.

If I were to turn this into the tree that I want, it'd look like this:

weapon (as there are ten items that have the weapon property)

tool (as there are six items with the tool and weapon properties)

food

fruit

tool

It's simple to do by hand, but I can't seem to wrap my head around putting this into program form. Any help?

答:
You can implement thus recursively:

Find the most common property in the set of objects.

Make this property a (new) root of the tree.

Divide the set in a subset of objects that have the property and a subset of objects that don't have the property.

Recurse: create a tree of the subset of objects that have the property (removing this property from all objects) and set that tree as a subtree of the newly created root.

Repeat steps 1..5 with the other subset (the objects that didn't have the selected property) until the set its empty.

ContentLicense: CC BY-SA 3.0


问:
Why C language is taught as the basis of Computer Programming Languages?
I often wondered why C Language is taught as the basis of programming languages everywhere. There are a lot of modern languages like Java, Python etc. which makes the syntax and programming easier. Why are we still holding the C Language up in the front as the basics of programming languages?</p>

答: C is often taught as the first language and often together with some other computer science course. It makes the understanding of the compsci easier and you also are closer to the hardware then Java and other languages. </p>


问:
Haskell's ':' operator
I am currently studying about pattern matching in Haskell from here. The author gives an example of the implementation of "head" function (which returns the first element of a list) as following:

```<code>head' (x:_) = x
</code>```

He kind of explains the use of the operator but it's not clear to me. I understand that we can use it to append elements at front of a list:

```<code>5:[6,7] will give [5,6,7]
</code>```

I can't see though how we can use the ':' operator as a part of the argument (x:_) or (x:xs) in general.

How does that binding mechanism that binds the first element to x work?

答:
(:) is not a regular operator; it's a data constructor. Lists are constructed using (:) at the base level. This means that patterns can be matched to the input depending on the input. This works with all datatypes with constructors.

Here are some examples, illustrating that all constructors can be used in this way for patterns:

```<code>removeJust (Just n) = n
removeJust Nothing  = error "Can't remove from Nothing"

head (x:xs) = x
head []     = error "Oh, no!"

tail (x:xs) = xs
tail []     = error "Oh, no!"
</code>```

In each case here, a constructor is used to extract, or match, values from the data structure in some way. Only the constructor can be used in this pattern match, thus (:), Just and Nothing are all constructors that can be matched.

In fact, we can make our own List datatype to illustrate how that works:

```<code>data List t = Empty | Link t (List t)
-- Imagine Empty = [], Link 6 Empty = [6] = 6 : []
headList :: List t -> t
headList (Link x xs) = x
headList Empty       = error "Oh, no!"
</code>```

This is essentially the list datatype. Of course, it's a builtin type, so it has it's syntactic sugar, but it's all the same in the end.

Title: Haskell's ':' operator

Body:
(:) is not a regular operator; it's a data constructor. Lists are constructed using (:) at the base level. This means that patterns can be matched to the input depending on the input. This works with all datatypes with constructors.

Here are some examples, illustrating that all constructors can be used in this way for patterns:

removeJust (Just n) = n
removeJust Nothing  = error "Can't remove from Nothing"

head (x:xs) = x
head []     = error "Oh, no!"

tail (x:xs) = xs
tail []     = error "Oh, no!"

In each case here, a constructor is used to extract, or match, values from the data structure in some way. Only the constructor can be used in this pattern match, thus (:), Just and Nothing are all constructors that can be matched.

In fact, we can make our own List datatype to illustrate how that works:

data List t = Empty | Link t (List t)
-- Imagine Empty = [], Link 6 Empty = [6] = 6 : []
headList :: List t -> t
headList (Link x xs) = x
headList Empty       = error "Oh, no!"

This is essentially the list datatype. Of course, it's a builtin type, so it has it's syntactic sugar, but it's all the same in the end.


问:
Is it difficult to develop a programming language which is closely related to human language?
Will it be difficult in developing a programming language which is much more closer to our language ?

It was just to know the view of programmers across the globe towards the natural programming language.Thanks for giving me your views on this .

答:
Things like have been tried but the chances are that even if you solve the hard problem of parsing natural language and intepreting it into something meaningful (there's a walth of reading out there on NLP - natural language processing), the you will have another problem whether it will be any good at programming with.

Natural language is intended to cover a very broad domain (all of human experience) while conveying subtlety of meaning. In order to do that, it relies heavily on context: shared points of reference between interlocutors, and logical leaps and resolutions of ambiguities which both parties are confident the other can make.

Consider the following exchange:

A: It's French Onion soup today.

B: Oh, dear! Would you like one of my sandwiches?

Speaker B infers 'It' means "the soup on offer", presumably at the one source of food nearby; B knows speaker A doesn't like or can't eat onion soup and knows that A will therefore be hungry, so expresses sympathy. B has and is willing to forego a sandwich in order to prevent A being hungry, and thinks it possible that A will appreciate this offer.

This works for conversational human language where we are trying to express our own contribution conversationally and listen to what the other side has to say, but for programming we want to be very specific. Programming is the art of giving detailed instructions which will in given circumstances result in known outputs. In this case, it's harder to correct a computer conversationally at runtime. You don't want your business-critical software to make the wrong decision because it made the wrong guess when resolving natural language. It's also likely to be inefficient in terms of raw performance.

Basically, the problem domain of programming (as opposed to say, applications which accept user input like "Book a doctor's appointment on Tuesday") is a very specific problem which natural human language is relatively poor at addressing.

Humans are perfectly capable of writing in languages that machines can understand, at least now we have languages like C, Perl, etc. Computers are not good at understanding languages that come naturally to humans. Typically we come to a compromise on languages with parseable syntax and unambiguous meaning. Although we can use syntactic sugar (also known as DWIM or "Do what I mean") to smoothe over the trickier aspects of a language, we need to be careful to ensure that this is governed by rules transparent to both the computer and the programmer. Language significantly more 'human-like' will just result in us spending time guessing "OK, but what will the computer DO with that information?".

An excellent example of the border between the useful and the frustrating is this in JS. On the one hand this lets you get things done quickly without worrying too much about parameters. On the other, it's a magnet for action at a distance bugs that are really hard to track down when you think this refers to one thing but in fact it refers to something else.

In fact, giving clear instructions can sometimes be hard among humans, and real words like "this" are often misinterpreted - we're not good at communicating our expectations first time round and the discipline of translating it into unambiguous is a vital part of programming.


答:
You're thinking about this in a very imperative mindset.
(:) does not do anything.

It means that whatever comes before it is the first element of the list.
2:[3, 4] is   [2,3,4]

This is important to consider when looking at the pattern matching.

```<code>fun (x:xs) = ...
</code>```

This is a way of giving the first element and the tail of a list a name.
There's nothing more to it.

Title: Haskell's ':' operator

Body:
I am currently studying about pattern matching in Haskell from here. The author gives an example of the implementation of "head" function (which returns the first element of a list) as following:

```<code>head' (x:_) = x
</code>```

He kind of explains the use of the operator but it's not clear to me. I understand that we can use it to append elements at front of a list:

```<code>5:[6,7] will give [5,6,7]
</code>```

I can't see though how we can use the ':' operator as a part of the argument (x:_) or (x:xs) in general.

How does that binding mechanism that binds the first element to x work?

Body:
You're thinking about this in a very imperative mindset.
(:) does not do anything.

It means that whatever comes before it is the first element of the list.
2:[3, 4] is   [2,3,4]

This is important to consider when looking at the pattern matching.

fun (x:xs) = ...

This is a way of giving the first element and the tail of a list a name.
There's nothing more to it.


答:
As others have pointed out, the operator : is a data constructor that allows to create a list by adding an element in front of an existing list.

The expression (or term) 1 : 2 : [] is actually a tree 1 : (2 : []), where

The root node is labeled with :

The root has two children: a leaf labeled with 1 and the subtree 2 : []

A term can be see as a data structure that denotes a value: the value is obtained by evaluating / reducing the term:

```<code>(1 + 2) + 5 => 3 + 5 => 8
</code>```

A term can also be used as a pattern against which we want to match values. For example: the term 1 : 2 : [] is a pattern that matches the list [1, 2].

Patterns can contain variables, e.g. x : y. This is a tree with a root node labeled with : and two leaves labeled with the variables x and y. You can define a substitution for variables, e.g. x --> 1, y --> 2 : []. With this substitution, the term x : y can be unified with the term 1 : 2 : [].

As you probably know already, the special variable _ is used when we are interested to find a substitution, but we are not interested in the actual substitution, i.e. we only want to know that there is one.

When defining a function in Haskell, each function left-hand side contains patterns that need to be matched against the actual arguments. If a substitution is found, then the right-hand side is evaluated, with the formal arguments replaced by the terms in the substitution.

So, a term can be used for pattern matching (e.g. in left-hand side of a function equation) or for denoting a value (e.g. in the right-hand side of an equation). In order for a term in the right-hand side to represent a value, it must

either contain no free-variable, as in 1 : 2 : []

or contain only free variables that have been bound by matching the left-hand side with the arguments of the function call.

Summarizing: you use the same syntax for patterns and expressions because in both cases you are building terms, even though these are used in different ways.

Title: Haskell's ':' operator

Body:
As others have pointed out, the operator : is a data constructor that allows to create a list by adding an element in front of an existing list.

The expression (or term) 1 : 2 : [] is actually a tree 1 : (2 : []), where

The root node is labeled with :

The root has two children: a leaf labeled with 1 and the subtree 2 : []

A term can be see as a data structure that denotes a value: the value is obtained by evaluating / reducing the term:

(1 + 2) + 5 => 3 + 5 => 8

A term can also be used as a pattern against which we want to match values. For example: the term 1 : 2 : [] is a pattern that matches the list [1, 2].

Patterns can contain variables, e.g. x : y. This is a tree with a root node labeled with : and two leaves labeled with the variables x and y. You can define a substitution for variables, e.g. x --> 1, y --> 2 : []. With this substitution, the term x : y can be unified with the term 1 : 2 : [].

As you probably know already, the special variable _ is used when we are interested to find a substitution, but we are not interested in the actual substitution, i.e. we only want to know that there is one.

When defining a function in Haskell, each function left-hand side contains patterns that need to be matched against the actual arguments. If a substitution is found, then the right-hand side is evaluated, with the formal arguments replaced by the terms in the substitution.

So, a term can be used for pattern matching (e.g. in left-hand side of a function equation) or for denoting a value (e.g. in the right-hand side of an equation). In order for a term in the right-hand side to represent a value, it must

either contain no free-variable, as in 1 : 2 : []

or contain only free variables that have been bound by matching the left-hand side with the arguments of the function call.

Summarizing: you use the same syntax for patterns and expressions because in both cases you are building terms, even though these are used in different ways.


问:
Event Driven Objects/Framework on the Web
I am a desktop developer moving to web development. The guys who I am working with use procedural PHP, and coming from an event driven, objectified perspective (using WPF and C#.Net) I am completely lost in what seems like the Wild West of development.

Are there any language/framework combinations that allow some semblance of state between the client and server and 'persists' the objects? Is there a way to create a definition of an object that is synonymous between the client and the server?

Is there anything that incorporates testing and UI components as well?

I realize this is a somewhat broad and biased question, however it is one that I have not found any definitive answers for. Any advice and guidance would be thoroughly appreciated!

答:
I see you need a solution for both the UI and the server.
As far as event driven web development is concerned, you may try the EXTJS by Sencha. It a javascript based framework,standardized and one of the most preferred.

The best feature,which is the best according to me, is it can communicate with your server in variety of formats like the widely used XML and JSON. Considering this, it frees you  from worrying about your compatibility with the server implementation. You may write your server in any language and communicate to the client via XML or JSON.

It provides APIs for most of the events on the web, and allows you to implement your own. It is based on  OOP, so your inheritance works here too :).It is has support for the MVC pattern, which will be bit difficult to digest in the beginning , as it is a common perception MVC - on the client - really? But have faith once you get the hold of it, its a smooth ride.

Almost all events have listeners(AJAX implementation). The UI look and feel is brilliant, and you get the feature of in built themes. In addition to this you have community support, dedicated learning material and API documentation, huge number of examples and even support for mobile devices.

Having said that, it carries various licences, it does have a GPL3 as well , but with certain terms.

For your ease I am posting the link to both the framework as well as the licensing terms

Framework:
http://www.sencha.com/products/extjs/

License:
http://www.sencha.com/products/extjs/licensing


答:
Your best bet is to first learn JavaScript without any frameworks. It works both in the client and server side (as Node.js). JavaScript is Event Driven by itself so you won't face much issue here.

Since you are coming from a C# background and your team uses PHP, I would highly recommend the Dojo Framework. It works both on the client and server side or it can work on the client side and has integration with Zend PHP on the server side.

There are Widgets in Dojo inside the Dijit package, which are basically classes used for implementing UI (Controls in the C# World). Integrating with Zend has some interesting perks includidng the persistent state you are talking about.

Otherwise you could go for vanilla frameworks like jQuery and sync data with your PHP server using AJAX Calls.

Title: Event Driven Objects/Framework on the Web

Body:
I am a desktop developer moving to web development. The guys who I am working with use procedural PHP, and coming from an event driven, objectified perspective (using WPF and C#.Net) I am completely lost in what seems like the Wild West of development.

Are there any language/framework combinations that allow some semblance of state between the client and server and 'persists' the objects? Is there a way to create a definition of an object that is synonymous between the client and the server?

Is there anything that incorporates testing and UI components as well?

I realize this is a somewhat broad and biased question, however it is one that I have not found any definitive answers for. Any advice and guidance would be thoroughly appreciated!


答:
I feel like the best option would be to just admit the problem and promise to fix it quickly. People in general aren't interested why and how you made a mistake, the only exception being your manager for he needs to continuously assess you professional fit.

As for blaming the one who made a mistake, it's in human nature and you can't help it. The best advice is to build a mental barrier and try no to take it too personally, not to let their criticism "touch" you. It's difficult though.

Title: How do you explain the source of an identifed problem without making it an "excuse"?

Body:
As practicing (as much as I can at least) "egoless programming", I'm focused on solving problems whoever wrote the code related (if that person don't make dangerous code) and I like to understand the problem fully to be sure to solve the source of this problem.

However, when someone point my code to show an error, I often try to remember what was my mindset while writing the defect code and I try to explain it to the guy pointing the error to make clear what was the error source (for example when some names are badly choosen, you might use them in a way they were not intended too and with apparent success...).

Now, I do this by reflex and most of my coworkers does understand this reflex. But I also worked in companies where coworkers were in a mentality of blaming the people that made the identified problems, with or without humour (for me it have the same not-sane effect anyway).

In this kind of environnement, explaining why you got to write wrong code makes others think that you're trying to build an excuse. I remarked that most non-technical people (or non domain-expert, not sure, it's only personal experience) also react exactly like that when you try to explain why you did something wrong.

So, when dealing with this kind of people/environnement, how do you manage to explain the real source of the error without looking like "making an excuse"? (and is it even worth trying to explain?)


答:
Basically C is Every Programming Language minus the Frills.

For someone new to the world of Programming concepts like Polymorphism, Event Driven programming, Object Oriented Programming just don't make any sense.

Remember that for a long time Computer Science existed inside Mathematics until the hardware technology was brought to the world. So now, you need a way for people to instruct the computer to achieve a certain objective. Most introductory level courses start by teaching how to implement a simple algorithm (like a Fibonacci Sequence or Factorial or whatever) as a computer program. You start with things like loops, conditions, functions, arguments etc. Instead of Interfaces, Classes, Singletons etc.

Things like Object oriented programming, Closures etc are a way to manage your code and architect your software application. Its the loops, conditions and arithemetic that actually do the real work! C is really good at teaching these things helped by the fact that There is a small, fixed number of keywords.

Less Language Learning, more Language Using.

When you learn C you automatically learn other languages.

C has been the inspiration for many many programming languages that have similar syntax. Personally I came from C to JavaScript and I felt right at home. According to Wikipedia

C influenced  AMPL, AWK, csh, C++, C--, C#, Objective-C, BitC, D, Go,
Rust, Java, JavaScript, Limbo, LPC, Perl, PHP, Pike, Processing,
Python, Seed7, Verilog (HDL)!

When one tries Java / PHP / JavaScript / C++ after C, they just learn some new concepts like OOPS, Closures (or forget some like static typing) and don't re learn loops, conditionals etc.

C is still in rampant use today.

C is used for System Programming, Developing OSes, Developing Servers, Databases, even Browsers and Virtual Machines.

C is blazzzingly fast!

The world's most performant Servers are written in C.
Statistical, Mathematical and other Computationally intensive environments are written in C. The GNU Multi-Precision Library, the GNU Scientific Library, Mathematica, R language and MATLAB are completely or partially written in C

C has been used to actually make (not just influence) more languages.

You can find parsers for almost any language in C. The primary implementations of Python (CPython), Perl 5, R and PHP are all written in C!

C is almost exclusive for writing Device Drivers.

Whether Linux, Windows or Mac there is a great demand for C Engineers in Hardware companies and Software Companies making OSes for development of device drivers.

C is almost exclusive for writing code in Embedded Environments.

All your Micro Controllers, System on a Chip, and other Embedded hardware is written either in Assembly or in C. Infact this is a reason why many Electronics majors are also taught C.

The next great language will be again based off of C.

That doesn't sound too unreasonable. C was appeared in 1972. C++ appeared 11 years later. JavaScript appeared 23 years later and C# arose 28 years later! All of them very strongly linked to C. C has withstood the test of time and there is still many more C like languages to come.

C will teach you theory and application.

Most importantly, the responsibility of an academic setup is not just just to teach you skills the industry needs, or you would need for a job but also equip you with enough theoretical and analytic skills so you can still stay relevant navigating the changes of the future.

Title: Why C language is taught as the basis of Computer Programming Languages?

Body: I often wondered why C Language is taught as the basis of programming languages everywhere. There are a lot of modern languages like Java, Python etc. which makes the syntax and programming easier. Why are we still holding the C Language up in the front as the basics of programming languages?</p>


问:
MVC: Inserting a view from a SubController to its Parent controller
I have 2 controllers: 1 top level controller,MainController, and a SubController, which MainController has an instance of and controls. The SubController has a Subview which goes inside the MainView as some sub web element.

What is a good way to insert the SubView into MainView? I can think of:

1) I can give SubController and SubView a reference of the MainView and append to it in the Subview

2) Return the html from the SubView rendering function to SubController, which returns to it to the MainController -> MainView ->  render

Or is there a much better way?

答:
For the cleanest separation between the Main and Sub View/Controller, the SubView/SubController combination should be unaware of the existence of the MainView and MainController. That way you leave open the possibility to re-use the SubView/SubController elsewhere in the application.

There are different ways to do the rendering of sub-views, each with advantages and disadvantages.

The most important thing to keep in mind is that if you are generating your HTML on the server, then the View components should not know (nor care) if their output is sent directly to the client's browser or if it will be embedded in a larger view.

You could also say that every View is ultimately embedded within a master-View that only tags on the HTML header and body elements.

Then you can either let the Controller components render their sub-Views or you can do that in the View components.

My preference is to do it in the View, as it is all display related, which is the responsibility of the View components of MVC. On the other hand, that results in quite a bit of programming logic in the View, which many are not really comfortable with and which is not that well supported by the templating engines that are commonly used for generating views.


问:
Solving a Sudoku variant with an unknown element
I recently stumbled upon a special Sudoku variant and am now struggling to effectively solve it programatically.

Consider the following initial 6x6 grid:

The rules

The red question mark is supposed to represent our secret digit. The secret digit behaves like a normal digit. That is, it has an actual value between 1 and 6, but this value isn't revealed to the player. In this game type, if we create a collision, the newly placed digit would become a neutral element that can be seen as a joker, not colliding with any other digit. For instance, if the secret digit actually was a 6 and we placed a 6 in its row, it would become a neutral element (and we would therewith also know what the secret digit is). We can generate a maximum of one neutral element (meaning that we can only create one collision), a second collision would render the grid unsolved.

Side note: Naturally, this interactive game type doesn't make sense to be printed on a piece of paper; it would e.g. require a client-server infrastructure for the secret not to be revealed to the player.

Analysis

Since the secret digit follows the basic rules, we can deduce that it can't be a 4 in the example grid, but every other digit could be possible. We can also see that there isn't a unique solution; in fact, there usually are hundreds of possible solutions. In a 6x6 initial grid, there is always one secret digit and 6 digits that are pretty randomly placed in the grid (without colliding with each other). This means, the secret could be exposed right off the bet, but we will dismiss the trivial case since it's not fun at all :)

Solving strategy

The most promising strategy would be to find out the secret digit as quickly as possible. That is, we would place digits in its row, column or box until either every possibility is exhausted, or we create a collision. As soon as we know what the secret is, we can solve the puzzle like a normal one (simply ignoring the neutral element if present).

The problem

I want to write an algorithm that finds the secret digit without creating an unsolvable board.

I wrote a rather blunt program which starts by identifying the fields in the secret's row, column and box with the fewest blockers. It then inserts digits in those fields, in an order from fewest blockers to most blockers until the secret can be deduced by collision or exhaustion. In the example grid, it would do something like this:

The blue digits would be placed in ascending order (starting with 1).
My current alogrithm produces an unsolvable board about 20% of the time, which is unacceptable to me. And that's why I'm asking the question:

What would be a smarter approach, minimizing or even eliminating the possibility of creating an unsolvable puzzle?

P.S.: I appreciate every type of answer; theoretical prose, pseudo-code or real code in a popular language is all fine, I simply want to get the gist of which fields/digits to select for the starting strategy.

答:
I don't think i understood the WildCard concept to well. Maybe some images of sample configurations on the board would help?

There are already well established Sudoku Solving Algorithms that exist. Some like

Backtracking.

Keep placing numbers one by one until you reach an unsolvable position, then retrace your last step and continue.

Constraint Solving

Each cell has many constraint because of the row, the column and the group of cells. Map out all the constraints of each cell and begin solving the cell where the answer is unique for that contraint. Keep udating the other contraints as numbers are added.

You can find more here

Since there are well established algorithms, one strategy to tackle this problem is to modify the above strategies to include this. Eg: this cell would impose no constraint in its rows, columns and the bigger cell.

I will try to edit with pseudo code for a constraint based solution if I have time.


问:
Naming self or this something else, a good idea?
I'm finding that my code becomes more readable when I make a local reference to this/self, and/or call it something that makes sense in the context. "self" or "this" doesn't really indicate what kind of object we are dealing with, in the same way as "default" or "standard" or "master" is unclear because it's not explicit.

For example, in Python code, instead of naming the instance reference "self", you could name it something else:

```<code>class User:
    def getFullName(user):
        return user.firstName + " " + user.lastName
</code>```

What are the arguments for naming it self, instead of something more explicit, like "user" in this case?

A similar example in JavaScript when doing a manual mixin:

```<code>function asUser(obj, name) {
    var user = obj;
    user.name = name;
    return user;
}
</code>```

I guess in JavaScript this is less controversial because there is not strong tradition of using a certain naming, as in the case of "self" in Python.

答:
In general I feel it might make your code less readable. Simply because inside different classes you're going to use different words to reference the instance. I refactor a lot of code for a living and a this, self or even _this is immediately scanned by me as the reference to the instance.

This may not exactly fit your requirements but in JavaScript we do have to frequently rename this! The this keyword loses context inside callbacks and refers to window / global!

https://stackoverflow.com/questions/337878/var-self-this?lq=1
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

```<code>var _this = this;
var self = this;
</code>```

Is how most JS libraries roll!

Body:
In general I feel it might make your code less readable. Simply because inside different classes you're going to use different words to reference the instance. I refactor a lot of code for a living and a this, self or even _this is immediately scanned by me as the reference to the instance.

This may not exactly fit your requirements but in JavaScript we do have to frequently rename this! The this keyword loses context inside callbacks and refers to window / global!

https://stackoverflow.com/questions/337878/var-self-this?lq=1
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

var _this = this;
var self = this;

Is how most JS libraries roll!


问:
String[] args vs (String . . . args)
When programming for android, whenever I use an AsyncTask the doInBackground method looks like this.

```<code> protected String doInBackground(String... args)
</code>```

But when using the arguments anywhere in that block I can access them like a normal String array for example in my program

```<code>        @Override
    protected String doInBackground(String... args)
    {
        String details = "";
        try
        {
            details = facade.getRecipeDetails(args[0]);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return details;
    }
</code>```

Which works fine and I have no problem dealing with it. But I'm wondering why they use (String . . . args) instead of a normal array of Strings. Is it just because in the calling method you can just write something like:

```<code> new AsyncHandler.execute("argument1","argument2","argument3",...)
</code>```

instead of creating a new array to pass the arguments? Though we could write

```<code>new AsyncHandler().execute(new String[]{"Argument1","Argument2"});
</code>```

which is a bit more verbose.

Are (String ...) and String[] synonymous in how they work, but the argument passing is just easier using the former because there is no need to create an array? As far as I can tell, the former also gets translated to a string array in the background so would they both compile to the same code and it's just 'syntactic sugar'?

答:
(String ...) is an array of parameters of type String, where as String[] is a single parameter.

Now here String[] can full fill the same purpose here but (String ...) provides more readability and easiness to use.

It also provides an option that we can pass multiple array of String rather than a single one using String[].

Title: String[] args vs (String . . . args)


答:
Yes and No.

If all you mean is it's like asking Siri to do stuff, you're going to be disappointed.

After all, people have been trying to make computer languages human-like for a long time.
Just look at Cobol.

On the other hand, if you have something in your head, and you're trying to teach the computer how to do it, there has to be a fairly good match-up between the concepts you are thinking about, and the nouns and verbs available in the programming language.

In fact, there's no other way to write any program.
The first thing you do is define variables, data structures, functions/methods, which correspond to what you're thinking about, so you can tell the computer what to do.
You're no longer working in Java, Python, Fortran, or whatever you started in.
That's just the base language.
You're working in the particular language you taught it.

That doesn't mean just any Joe Schmoe can walk up and understand your code.
Just as there was a learning curve on the machine's part, there is a learning curve on his part too.
People who think they shouldn't have to spend time learning (in order to get the reward of higher productivity) are just not being serious.

At the same time, you need to be a teacher.
Just as you taught the computer what you are talking about, you also need to teach other people.

Title: Is it difficult to develop a programming language which is closely related to human language?

Body:
Will it be difficult in developing a programming language which is much more closer to our language ?

It was just to know the view of programmers across the globe towards the natural programming language.Thanks for giving me your views on this .


问:
Is there a useful correlation between choice of web-browser/search engine and good quality programmers?
After a round of interviews earlier this year, which included some practical questions with access to a computer, I noticed that, at least for the applicants we were seeing, there was a high inverse correlation between quality of applicant and the explicit choice of Bing/IE as the stack for search/browsing the web. That is, a large number of applicants specifically searched for IE to use as a browser when browsing the web, and specifically used Bing as the search engine (even typing in Bing in the Google search box, before starting a search)

Is this just an outlier, a fluke, or is there some sort of information I can obtain from this observation? So far, my best candidates are:

Yes, there is a high correlation between good programmers and choice of web browser/search engine

There is some training program, or community, which advises using IE/Bing during interviews, and I just happened to run into a poor selection from that group

Something else is going on, that I don't know about, but someone here might know.

So, to repeat, the question is: is there more than coincidence at work here, and, if there is, what's going on?

答:
I think there are a lot of potential confounding variables here:

1) Using Bing over Google could be seen as a good thing.  The general suggestion is that IE is bad because it means that the person has failed to make a choice, but the same is surely true of Google, more a defacto standard for search than IE is for browsing these days.  Someone using Bing has likely made a concious choice which suggests the sort of experimenting / assessing which is generally regarded as positive.

2) An increasing number of companies (we are one) mandate non-IE browsers by default for security reasons.  In this instance the logic reverses and using IE becomes the choice rather than Firefox.

3) If a developer spends a lot of time developing to target a certain browser then I'd see it as a good thing that they use that browser by default.

4) I suspect there is a certain anti-MS bias generally which looks down on IE and Bing which, once you'd noted this once may have lead to confirmation bias.  This needs to be excluded.

5) Was the computer set up in such a way that IE was easier to find?  In the toolbar or on the desktop?  It maybe the thinking was less about which browser, how do I find the net as fast as possible?

And on top of that you'd have to find some workable metric for assessing programmers as good or bad...

It's a mildly interesting idle observation but I wouldn't put any stock in it and I think firming it up would be far more effort than was warranted.

For what it's worth my gut feel is that search engine choice would be irrelevant (point 1 and point 4 above being significant for me), browser choice would show a weak inverse correlation between IE users and ability but nothing strong enough to usefully use.


答:
This is a huge mistake.  self is a well-worn convention in Python and so any Python programmer who encounters this code is going to immediately be confused.  Any experienced programmer will see self and will instinctively think "I am looking at a method definition and this particular line is accessing an attribute of the object".

Name it something else, and you've lost the advantage of that instinct.  For a two line method as above, this will produce a few minutes head scratching.  If the method is a complex one, maybe twenty lines, it will produce a lot more confusion, and the average python programmer will repeatedly end up thinking "oh wait...user is the self object."  That will waste time if nothing else.

Confusion will multiply if any code outside the object uses user as a name, which is, of course, the obvious thing to name an object of type User outside the class.  This means you will continually be thinking "Oh wait, am I inside the class or not?"

Speaking as a long term C++ and then Python coder, your first example just seems weird.  My brain does not even want to think of it as a method despite the fact that it knows it is.  user looks like something being "passed in" from outside the object, and it is actual mental work to realize that it is not something external to the object.

Convention is massively important in code readability.  It's why we have style guides.  One thing that earns python's reputation for readability is that it has a clearly defined style guide that most conform to.  self is a part of that.

Title: Naming self or this something else, a good idea?

Body:
I'm finding that my code becomes more readable when I make a local reference to this/self, and/or call it something that makes sense in the context. "self" or "this" doesn't really indicate what kind of object we are dealing with, in the same way as "default" or "standard" or "master" is unclear because it's not explicit.

For example, in Python code, instead of naming the instance reference "self", you could name it something else:

```<code>class User:
    def getFullName(user):
        return user.firstName + " " + user.lastName
</code>```

What are the arguments for naming it self, instead of something more explicit, like "user" in this case?

A similar example in JavaScript when doing a manual mixin:

```<code>function asUser(obj, name) {
    var user = obj;
    user.name = name;
    return user;
}
</code>```

I guess in JavaScript this is less controversial because there is not strong tradition of using a certain naming, as in the case of "self" in Python.


问:
TDD with repository pattern
In my new project, I decided to try with TDD. And in very beginning I encountered a problem. First thing that I want to do in my application is to give ability to read data from data source. For this purpose, I want to use repository pattern.
And now:

If test are for real implementation of repository interface, I will be testing class that has access to database, and I know that I should avoid that.

If test are for not real implementation of repository pattern, I Will be testing well... just mock. There will be no any piece of production code tested in those unit tests.

I'm thinking about this from two days and still cannot come up with any reasonable solution. What I should do?

答:
Don't test trivial or obvious repository methods.

If the methods are trivial CRUD operations, all you're really testing is whether parameters are mapped correctly.  If you have integration tests, such errors will become immediately apparent anyway.

This is the same principle that applies to trivial properties, like this one:

```<code>public property SomeProperty
{
    get { return _someProperty; }
    set { _someProperty = value; }
}
</code>```

You don't test it, because there's nothing to test.  There's no validation or other logic in the property that needs to be verified.

If you still want to test those methods...

Mocks are the way to do it.  Remember, these are Unit Tests.  You don't test the database with unit tests; that's what Integration Tests are for.

More Information

The Full Stack, Part 3: Building a Repository using TDD (start watching at about 16 minutes in).

Title: TDD with repository pattern

Body:
Don't test trivial or obvious repository methods.

If the methods are trivial CRUD operations, all you're really testing is whether parameters are mapped correctly.  If you have integration tests, such errors will become immediately apparent anyway.

This is the same principle that applies to trivial properties, like this one:

public property SomeProperty
{
    get { return _someProperty; }
    set { _someProperty = value; }
}

You don't test it, because there's nothing to test.  There's no validation or other logic in the property that needs to be verified.

If you still want to test those methods...

Mocks are the way to do it.  Remember, these are Unit Tests.  You don't test the database with unit tests; that's what Integration Tests are for.

More Information

The Full Stack, Part 3: Building a Repository using TDD (start watching at about 16 minutes in).


问:
where should put showSchedule method in school system
In my school management system I have this partial  class diagram:

1- In one use case student want to see his schedule of classes in week. this is what i suppose to do:

get student object from session and call method getSchedule() on that and it will give me schedule(this method calls StudentCourse, Course for getting schedule).

Is this good place to put getSchedule() method or I should place it elsewhere?

..................................................

2- In another use class student's parent want to see his child class schedule, I plan to do something like this:

Because I have some use cases that parent want to see some other student information(course mark...), I create interface StudentParentInterface that have method getSchedule() and other methods and student implement StudentParentInterface, then parent has reference to StudentParentInterface not student obj directly.

parent call getSchedule() method on StudentParentInterface, is this correct?

答:
It's not clear to me if you're following an OO methodology that uses analysis first. That way, you first have classes that represent only the problem domain. Then you consider the same software classes, but you're allowed to deviate from that.

getSchedule() could be a method in a so-called Use-case Controller also know as Front Controller which can be seen as a special case of the Mediator pattern.

TL;DR

If you're having trouble finding the right place to put a method because it doesn't really go with any of the existing classes responsibilities (it violates the cohesion principle), then it's OK to create a separate class that handles that function. Craig Larman calls this a Pure Fabrication, or a class that doesn't map to the problem domain. In your case, you could call it ScheduleManager.


问:
How to explain DependencyProperty using real world analogy?

How to explain DependencyProperty using real world analogy?

Why is it needed?

答:
For a real-world analogy, I guess I would go with a Phone Book entry.

There are lots of people/phone numbers in the world, but to be found by everyone you post your number in the phone book.

Likewise, there are many regular properties that exist, and items that are aware of them know they exist and can use them, but a DependencyProperty is something that the entire application is aware of and can lookup when needed.


问:
Should we refactor our existing codebase to use functional programming, especially streams?
We have a large project written in PHP. It almost exclusively uses imperative operations, as in example 1. Should we refactor our existing code to use functional operations? Do you think that the code in example 2 is easier to maintain?

Example 1 - imperative

```<code> $cookieString = '';
 foreach($cookieArray as $cookieName => $cookieValue) {
   if($cookieString != '') {
     $cookieString .= '; ';
   }
   $cookieString .= $cookieName.'='.$cookieValue;
 }
 return $cookieString;
</code>```

Example 2 - functional

```<code> return KeyedStream::of($cookieArray)
                 ->mapEntriesToStream(function($cookieName, $cookieValue) {
                   return $cookieName.'='.$cookieValue;
                 })
                 ->joinToString('; ');
}
</code>```

答:
I admit, I love refactoring code - but chose wisely what to refactor and why.

Will the user of your code clearly benefit from the rewritten code? Will the user demand this new functional style code, or is it just a developer thing, to try coding with a different style? If there is no benefit for the user at all, except the code is now looking "nice", who is going to need it? You are replacing one fashion by another. And this is YAGNI - You Ain't Gonna Need It.

If the code basis is large, it means also this code is already developed over years, which means that the current code basis is already full of different code styles. And if we are talking about a large code basis, it sounds to me that you might have a lot of legacy PHP code too. You should be aware that refactoring/rewriting code will very probable introduce new errors. Every user hates new errors when the former code was working.

Are you prepared to fight the introduction for new errors? I mean, do you already have unit tests to detect errors or regressions? If you do not have unit tests, how will you be certain, that you understood the code you going to transformed into a functional style expression? Write unit tests! If this code is not testable - make it testable. As long as there are no unit tests for the fragments you want to refactor - do not refactor.

Refactoring is a lot less error-prone if your IDE supports factorings. Even then factorings aren't trivial and will often result in new unseen behavior.

Refactoring Java code: excellent IDE-Support (Eclipse, IntelliJ, Netbeans, ... )): just commit often (every ont to two minutes), while refactoring. Most refactorings are pressing some key-combinations.

Refactoring PHP code: I experienced bad IDE-Support: this means lots of manual steps, where each one could introduce new errors.

I do boy-scout-rule changes, whenever I touch some code nearby, I sometimes extract a method, rename a method, introduce a parameter instead of using a field in the class, change method signature, rename a field, ... But i never try to fix something I come across, what just looks wrong. If it is wrong, why does nobody complained about it, and when nobody complained, what may I missed? Write a test / tests for wrong looking code.

I do refactorings e.g. from GUI-god-class-code to patterns, if and only if, I must fix an error in this class and/or add a new functionality for that class. This is usually for code I inherited from other developers.

Could you maybe use the time you might spend on refactoring this code better used for something of more benefit to the user? Some of these benefits are also unit tests and continous integration.

If you like this functional style use it for the new code. But I find example 2 not any more readable than provided code in example 1.

hth


答:
Ask yourself honestly why you want to refactor. That's really important. then think what you're doing at your company - are you hired to write nice code, or to create good product.

I think too many developers get so caught up in the minutiae of the codebase that they forget what they're supposed to be doing - which is making something useful out of it. Its like a bricklayer worrying if he should change the clay mixture in his bricks when he's building a wall! (no brickie does that - they build the wall, then go and build more walls. Walls are important, the bricks only so as they make walls happen)

So question what your true motive is here. Is your code so difficult to understand that changing things is too costly? Is your code so rubbish that you cannot understand it to change anything? If the answer is no, then spend your efforts doing something useful.

Title: Should we refactor our existing codebase to use functional programming, especially streams?

Body:
We have a large project written in PHP. It almost exclusively uses imperative operations, as in example 1. Should we refactor our existing code to use functional operations? Do you think that the code in example 2 is easier to maintain?

Example 1 - imperative

```<code> $cookieString = '';
 foreach($cookieArray as $cookieName => $cookieValue) {
   if($cookieString != '') {
     $cookieString .= '; ';
   }
   $cookieString .= $cookieName.'='.$cookieValue;
 }
 return $cookieString;
</code>```

Example 2 - functional

```<code> return KeyedStream::of($cookieArray)
                 ->mapEntriesToStream(function($cookieName, $cookieValue) {
                   return $cookieName.'='.$cookieValue;
                 })
                 ->joinToString('; ');
}
</code>```


问:
What are the advantages of a 3 stage environment for SAP/BI development?
I have recently joined a team in which the developers were able to work completely in live production to produce business intelligence products for customers.

Recently, management, at the advice of SAP, have moved the team to a 3 stage environment

Develop

Test

Production

which require transports between each layer.

The team have accepted this new constraint begrudgingly and no firm business case has been explained to them as to the benefits.

Can anyone articulate the advantages of the 3 stage environment or point me to a white paper/case study they recommend?

答:
Deploying newly developed features straight into a live production system is extremely risky, in whichever language or platform you choose, because you are not able to test the new features or changes before the current users of the system are exposed to them.

With this in mind, it becomes clear why you should at least separate production and development environment, and choose appropriate times to deploy (transport) from development to production.

However, there are also good reasons to separate even further, and have a testing environment as well. Since complex systems usually require manual testing to completely check it (which may even be done by a team of testers and/or the customer), having a separate test environment allows you to have a stable build of the system for manual/integrated/acceptance testing, while the development is free to continue at its own environment. By "stable", not only it means that the features were already unit-tested by the developers (at the development environment), but also for SAP R/3, it means that there will be no dumps because someone is activating development objects while there are users running them (LOAD_TYPE_VERSION_MISMATCH).


问:
How to Keep Track of Thread Safe Code in a mostly Thread Unsafe Legacy Rich C++ Code Base
For large legacy C++ code bases, notions like Herb Sutter's "const means threadsafe" don't seem to help much, because there can be an overwhelming amount of code in const functions which are modifying state with no synchronization.  And even if legacy code wasn't a problem, for a class like a ThreadSafeQueue, you wouldn't want the push_back function to be const just because it is threadsafe.

Is there a method for keeping track of which functions are intended to be threadsafe, ideally leveraging the compiler to help enforce it?  Is there some way to fake an introduction of a new keyword like "threadsafe" that works similarly to const (i.e. compiler will give an error if a "threadsafe" labeled function calls any function not tagged as threadsafe)?

Perhaps my best bet is to just tag functions with a standard comment, perhaps using something like doxygen?  So a special "threadsafe" tag in a comment instead of the const keyword would mean "immutable or internally synchronized".

Anyone have experience with the process of adding multithreading to a large legacy code base that could share what worked and what didn't?

答:
One way to add multithreading to an older application is to use multiple processes and inter-process communication. This allows you to isolate the code in question, serializing communication with it, and if the code has bugs, memory leaks, etc, you can kill the process and restart it automatically. This works if the IPC overhead is worth the extra safety.

Another option is to write a wrapper API that is thread safe, but communicates with an non thread safe inner library, using serialization or queuing techniques. Watch out for deadlock.

I don't think C++ is going to help you improve the thread safety of the code, just by using the compiler. You have to review and potentially rewrite every line.


问:
Can most compilers check for errors?
I am a beginner at programming; so far all the compilers I have used can check for errors, and can refer to the line with the error. Are there any compilers, maybe for a certain language, that do not do this? at least at the professional level? The error-checking is great.</p>

答:
The answer is yes and no.

Yes, compilers will report locations with errors

A compiler stores a piece of data that represents the program you wrote. Remember, a compiler isn't magical it's just another program working just like the one you wrote! This piece of data will "tag" the relevant areas of code with locations. During compilation if the compiler encounters an error it's very easy to spit out the tagged location and so pretty much all of them do.

If your program does really crazy things, like generate code or let the compiler infer and generate parts of your program then sometimes the line numbers are utterly useless, but they're still there!

In fact, compilers usually give a lot more than just the line number. They try to tell you what exactly went wrong and why it happened. How successful they are varies a lot. A compiler that I worked with for example would occasionally just barf

```<code>Error:some line: internal failure
</code>```

It's error handling algorithms were a bit dodgy to say the least. Most are very good though.

No, Not every language gets as much error checking

This is actually somewhat of a religious war in the programming world. How much checking should your compiler do? A compiler can't magically detect all errors, so really it just forces you to follow a bunch of rules it decides upon. The goal is that these rule limit you to writing "good" programs. The problem is those rules will always cut out a bunch of perfectly reasonable programs!

Some software developers want their compilers to back off and just let them deal with making their programs correct. This means it's easier to write a legal program, but you have to work a lot harder to ensure it's correct.

Some software developers want their compilers to check as much as possible. They have to work a lot harder to write the original program so that it follows all the rules of the compiler. Once it compiles though, they don't have to test as much (if at all) because the compiler checked a lot of things before hand.

Deciding where on this spectrum you end up takes time. A lot of time. It also takes you experimenting with different languages to figure out what you want from a compiler. A lot of people even change their minds as time goes on. However, you can find professionals pretty much all along the spectrum.

TLDR

Yes, all compilers will give you information about your error. What errors compilers catch though varies a great deal.

Title: Can most compilers check for errors?

Body:
The answer is yes and no.

Yes, compilers will report locations with errors

A compiler stores a piece of data that represents the program you wrote. Remember, a compiler isn't magical it's just another program working just like the one you wrote! This piece of data will "tag" the relevant areas of code with locations. During compilation if the compiler encounters an error it's very easy to spit out the tagged location and so pretty much all of them do.

If your program does really crazy things, like generate code or let the compiler infer and generate parts of your program then sometimes the line numbers are utterly useless, but they're still there!

In fact, compilers usually give a lot more than just the line number. They try to tell you what exactly went wrong and why it happened. How successful they are varies a lot. A compiler that I worked with for example would occasionally just barf

Error:some line: internal failure

It's error handling algorithms were a bit dodgy to say the least. Most are very good though.

No, Not every language gets as much error checking

This is actually somewhat of a religious war in the programming world. How much checking should your compiler do? A compiler can't magically detect all errors, so really it just forces you to follow a bunch of rules it decides upon. The goal is that these rule limit you to writing "good" programs. The problem is those rules will always cut out a bunch of perfectly reasonable programs!

Some software developers want their compilers to back off and just let them deal with making their programs correct. This means it's easier to write a legal program, but you have to work a lot harder to ensure it's correct.

Some software developers want their compilers to check as much as possible. They have to work a lot harder to write the original program so that it follows all the rules of the compiler. Once it compiles though, they don't have to test as much (if at all) because the compiler checked a lot of things before hand.

Deciding where on this spectrum you end up takes time. A lot of time. It also takes you experimenting with different languages to figure out what you want from a compiler. A lot of people even change their minds as time goes on. However, you can find professionals pretty much all along the spectrum.

TLDR

Yes, all compilers will give you information about your error. What errors compilers catch though varies a great deal.


问:
AGPL - If I modify the source code do I HAVE to distribute it?
I am looking at extending/modifying a web application licensed under AGPL for my own business. The program that I am modifying doesn't interact with the public, but with my employees who will be using the program. Specifically, the program manages our inventory, manufacturing, orders, etc.

If I modify the source code of the program, do I HAVE to 1) advertise to the public that I have modified the program and 2) publish the modifications (source code)? Can someone point to where it says so in the license? I have been looking at https://tldrlegal.com/license/gnu-affero-general-public-license-v3-%28agpl-3.0%29 which explains that I can modify and that I can distribute, but my question is if I must.

Hopefully this makes sense, thanks.

答:
This is covered in the FAQ for the AGPL:

Q: How does this license treat commercial enterprise use over intranets and internal networks?

A: Simply, if run internally to a commercial company, then the company isn't required to release source code back to the world. The license requires that if a user downloads the source they have the right to make improvements and not release these modifications. GNU GPL software in general addresses this issue the same way. If an employee has access to the source and has the right to make improvements, the commercial entity could probably view this work as work for hire and owned by the company and not have to be released outside.

The realization here is that you, the company are only distributing the application to yourself in effect.  This means that you don't need to publish the code changes back to the public.

The AGPL is intended to force the public web apps (Google and the like) to publish their changes that use licensed software that is available to the public back to the public.  But, if the use is completely behind the corporate firewall and used only internally to the company, there is no requirement that the code be released back to the public because it is never distributed to the public as a webapp.

So no, you don't need to advertise to the public that you have modified the program, nor do you need to publish the modifications.  What is behind the corporate router stays behind the corporate router.  You, the company, are only distributing it to yourself; and you, the company, already have the source code and its changes.

Note that you would still be required to have your employees able to download the source of the original application, though it doesn't appear that you would need to make the modifications available.

Again from the FAQ:

Q: Can a commercial entity remove the download source button in a corporate intranet or internal networked environment?

A: No. Anyone who wants to use the software in a corporate intranet or internal network, must leave the download source button but doesn't have to make modifications available if not engaged in distribution. Anyone engaged in distribution beyond their enterprise must leave the download source button in place and make available the source for any modifications through this button.

ContentLicense: CC BY-SA 4.0


问:
What payoffs have you seen from taking care of technical debt?
This article on technical debt has some good points, including:

Working on the "technical matters" works best when it is driven by stories. The code base is probably in need of work everywhere, but the payoff will be received only where the code is going to be worked on for user-facing reasons. If no stories are going to pass through some crufty area, working on it is largely wasted.

Therefore, I prefer the approach of taking stories as usual (but probably fewer of them), and following the "boy scout rule" of leaving the campground better than you found it. In other words, wherever the stories lead us, let's write more tests, let's refactor more aggressively.

This approach has at least these advantages:

maintains "best sensible" flow of stories;

provides help from all team talent;

provides for whole team to learn how to keep code clean;

focuses improvement exactly where it is needed;

does not waste improvement that "may" be needed;

I've seen code quality have a very big effect on long-term productivity, so I am a believer that technical debt should be taken care of.  I think the post above makes sense, but I'm not so sure about the last two points.  I'm interested in finding out real experiences of benefits from cleaning technical debt, even if it was not related to user stories.

What positive benefits have you seen from cleaning up your code base and ridding yourself of technical debt? What methods did you use to get the work done?

答:
The biggest benefit an organization will receive as a result of paying down technical debt is avoiding the compound interest.  There is an example in the blog entry below that shows how the principal amount owed on a technical debt went from $160k to $430k in just five years.  It would take a full time programmer solely dedicated to servicing that amount of debt.  That will help put it in perspective for the decision makers!

From blog.acrowire.com.

OwnerDisplayName: Ted


答:
One technique if you've got a lot of thread-unsafe code is to only let one thread have access to it. If the other threads don't touch, the lack of safety is a non-issue. To make this work, you can then communicate with the rest of the application via message queues: the thread-safe parts can ask the thread-unsafe part to do some work by sending a message to it, and the thread-unsafe part can respond by sending a message back (which the thread-safe part might or might not stall waiting for, depending on what's really going on in the application).

The message queues must be appropriately guarded against multi-threaded access, of course, but they're quite a small piece of code and can have textbook lock semantics so you can get them right without too much trouble.

This is conceptually similar to running the code in another process and communicating via pipes, except you're not restricted to sending byte-serialized messages and can use something more structured instead.

The compiler cannot work out how to make code thread-safe by itself. It's just this software, y' know? It can give you tools to make it easier to do, less onerous, but it doesn't really understand what the code is supposed to do. All it can see is exactly what is written, and it's pretty much the ultimate in language lawyers. It's idea of what's right is not yours.

Title: How to Keep Track of Thread Safe Code in a mostly Thread Unsafe Legacy Rich C++ Code Base

Body:
For large legacy C++ code bases, notions like Herb Sutter's "const means threadsafe" don't seem to help much, because there can be an overwhelming amount of code in const functions which are modifying state with no synchronization.  And even if legacy code wasn't a problem, for a class like a ThreadSafeQueue, you wouldn't want the push_back function to be const just because it is threadsafe.

Is there a method for keeping track of which functions are intended to be threadsafe, ideally leveraging the compiler to help enforce it?  Is there some way to fake an introduction of a new keyword like "threadsafe" that works similarly to const (i.e. compiler will give an error if a "threadsafe" labeled function calls any function not tagged as threadsafe)?

Perhaps my best bet is to just tag functions with a standard comment, perhaps using something like doxygen?  So a special "threadsafe" tag in a comment instead of the const keyword would mean "immutable or internally synchronized".

Anyone have experience with the process of adding multithreading to a large legacy code base that could share what worked and what didn't?


问:
If MVC is "Separation of Concerns" then why was Razor Syntax introduced?
My question is related to MVC design pattern and Razor Syntax introduced by Microsoft.

While learning MVC design pattern I was told that the idea is based upon a principle known as Separation of Concerns.

But Razor Syntax allows us to use C# in Views directly.

Isn't this intersection of concerns?

答:
You are conflating the Razor syntax with separation of concerns.

Separation of concerns has to do with how you structure your code.

Being able to use C# in views doesn't prevent that. It has nothing to do with separation of concerns as such.

Sure, you can structure the code in your view to not comply with separation of concerns, but what about C# code that is used for display purposes only? Where would that live?


问:
License of library used by one library include in my project
I am developing a small project to sell and I have used several Java libraries, mostly with LGPL or Apache 2.

And I have one question, for example, I am using jasypt, wich is an Apache 2 license library, but this requires the commons collections library, also Apache 2.

Do I need to put in my license form the common collections library?.

```<code>Apache 2.0 License
Used in  Apache Commons Codec version 1.10 , Joda-Time version 2.6 , Xerial Sqlite JDBC version 3.8.7 and Jasypt version 1.9.2

<LICENSE GOES HERE>

BSD License
Used in  MigLayout version Swing 4.2 and JDatePicker version 1.3.4

<LICENSE GOES HERE>

LGPL 2.1 LICENSE
Used in PortableRXTX and RXTX version 2.2-pre2

<LICENSE GOES HERE>
</code>```

Also the LGPL and the Apache force me to put the source code and the modifications, but if I have used the binaries without compiling or modifiying anything, Do I need to include the source? If I need could I post a link to githubs repos with the latest version of the library?

答:
In your license form, you should mention all libraries that you are distributing as part of your application.

Libraries that you use but not distribute (for example, because you assume they will be already installed as they are commonly part of the JRE/runtime environment) you can mention but without license details.

Making it a habit to include all libraries you distribute with full license details makes it harder to miss one where the license requires that is is mentioned also in the application.

Mentioning the dependencies that you don't distribute is mostly a courtesy to their authors and can be a help to people with an unusual setup that happen to miss one. Mentioning licenses for these is a bit misleading, because your users might have a different version under a different license.

Technically the LGPLv2 requires that if you provide binaries, that you also must provide the source code.

However, if you did not make any changes to the code, then it is in practice sufficient to provide a link to the original project where you got your binaries/sources from.

The Apache 2 license does not require you to distribute the source of unmodified libraries, but here it is also a gesture of goodwill to provide a link to the original project for those that want to retrieve the sources.

Often, these links are provided together with the license information for the libraries.


答: You never need to publish anything with the (A)GPL. You only ever need to make available the source code to those persons to whom you also make available a binary (and with the AGPL also to those users whom you let use your binary over the network).

Title: AGPL - If I modify the source code do I HAVE to distribute it?

Body:
I am looking at extending/modifying a web application licensed under AGPL for my own business. The program that I am modifying doesn't interact with the public, but with my employees who will be using the program. Specifically, the program manages our inventory, manufacturing, orders, etc.

If I modify the source code of the program, do I HAVE to 1) advertise to the public that I have modified the program and 2) publish the modifications (source code)? Can someone point to where it says so in the license? I have been looking at https://tldrlegal.com/license/gnu-affero-general-public-license-v3-%28agpl-3.0%29 which explains that I can modify and that I can distribute, but my question is if I must.

Hopefully this makes sense, thanks.


答:
What a repository does is translate from your domain onto your DAL framework, such as NHibernate or Doctrine, or your SQL-executing classes. This means that your repository will call methods on said framework to perform its duties: your repository constructs the queries needed to fetch the data. If you're not using an ORM-framework (I hope your are...), the repository would be the place where raw SQL-statements are built.

The most basic of these methods is the save: in most cases this will simply pass the object from the repository onto the unit of work (or the session).

```<code>public void Save(Car car)
{
    session.Save(car);
}
</code>```

But let's look at another example, for example fetching a car by its ID. It might look like

```<code>public function GetCarWithId(String id)
{
    return Session.QueryOver<Car>()
                    .Where(x => x.Id == id)
                    .SingleOrDefault();
}
</code>```

Still not too complex, but you can imagine with multiple conditions (get me all the cars made after 2010 for all brands in the 'Volkswagen' group) this gets tricky. So in true TDD fashion you need to test this. There are several ways to do this.

Option 1: Mock the calls made to the ORM framework

Sure, you can mock the Session-object and simply assert that the right calls are made. While this tests the repository, it is not really test-driven because you are just testing that the repository internally looks the way you want it to. The test basically says 'the code should look like this'. Still, it is a valid approach but it feels like this kind of test has very little value.

Option 2: (Re)build the database from the tests

Some DAL-frameworks give you the ability to build the complete structure of the database based on the mapping files you create to map the domain onto the tables. For these frameworks the way to test repositories is often to create the database with an in-memory database in the first step of the test and add objects using the DAL-framework to the in-memory database. After this, you can use the repository on the in-memory database to test if the methods work. These tests are slower, but very valid and drive your tests. It does require some cooperation from your DAL-framework.

Option 3: Test on an actual database

Another approach is to test on an actual database and isolate the unittest. You can do this in several ways: surround your tests with a transaction, clean up manually (would not recommend as very hard to maintain), completely rebuild the database after each step... Depending on the application you are building this may or may not be feasible. In my applications I can completely build a local development database from source control and my unittests on repositories use transactions to fully isolate the tests from each other (open transaction, insert data, test repository, rollback transaction).  Every build first sets up the local development database and then performs transaction-isolated unittests for the repositories on that local development database. It's a little slower then a pure Unittest but the tests are extremely valuable and catch a lot of issues.

Don't test the DAL

If you are using a DAL framework such as NHibernate, avoid the need to test that framework. You could test your mapping files by saving, retrieving and then comparing a domain object to make sure everything is okay (be sure to disable any sort of caching) but it's not as required as a lot of other tests you should be writing. I tend to do this mostly for collections on parents with conditions on the children.

When testing the return of your repositories you could simply check to see if some identifying property on your domain object matches. This can be an id but in tests it's often more beneficial to check a human readable property. In the 'get me all the cars made after 2010....' this could simply check that five cars are returned and the license plates are 'insert list here'. Added benefit is that it forces you to think about sorting AND your test automatically forces the sorting. You'd be surprised how many applications either sort multiple times (return sorted from the database, sort before creating a view object and then sort the view object, all on the same property just in case) or implicitly assume the repository sorts and accidentally remove that somehwere along the way, breaking the UI.

'Unit test' is just a name

In my opinion, unit tests should mostly not hit the database. You build an application so that every piece of code that needs data from a source does this with a repository, and that repository is injected as a dependency. This allows for easy mocking and all the TDD-goodness you want. But in the end you want to make sure that your repositories perform their duties and if the easiest way to do that is hit a database, well, so be it. I've long let go of the notion that 'unit tests should not touch the database' and learned that there are very real reasons to do this. But only if you can do this automatically and repeatedly. And weather we call such a test a 'unit test' or an 'integration test' is moot.

Title: TDD with repository pattern

Body:
In my new project, I decided to try with TDD. And in very beginning I encountered a problem. First thing that I want to do in my application is to give ability to read data from data source. For this purpose, I want to use repository pattern.
And now:

If test are for real implementation of repository interface, I will be testing class that has access to database, and I know that I should avoid that.

If test are for not real implementation of repository pattern, I Will be testing well... just mock. There will be no any piece of production code tested in those unit tests.

I'm thinking about this from two days and still cannot come up with any reasonable solution. What I should do?

Body:
What a repository does is translate from your domain onto your DAL framework, such as NHibernate or Doctrine, or your SQL-executing classes. This means that your repository will call methods on said framework to perform its duties: your repository constructs the queries needed to fetch the data. If you're not using an ORM-framework (I hope your are...), the repository would be the place where raw SQL-statements are built.

The most basic of these methods is the save: in most cases this will simply pass the object from the repository onto the unit of work (or the session).

public void Save(Car car)
{
    session.Save(car);
}

But let's look at another example, for example fetching a car by its ID. It might look like

public function GetCarWithId(String id)
{
    return Session.QueryOver<Car>()
                    .Where(x => x.Id == id)
                    .SingleOrDefault();
}

Still not too complex, but you can imagine with multiple conditions (get me all the cars made after 2010 for all brands in the 'Volkswagen' group) this gets tricky. So in true TDD fashion you need to test this. There are several ways to do this.

Option 1: Mock the calls made to the ORM framework

Sure, you can mock the Session-object and simply assert that the right calls are made. While this tests the repository, it is not really test-driven because you are just testing that the repository internally looks the way you want it to. The test basically says 'the code should look like this'. Still, it is a valid approach but it feels like this kind of test has very little value.

Option 2: (Re)build the database from the tests

Some DAL-frameworks give you the ability to build the complete structure of the database based on the mapping files you create to map the domain onto the tables. For these frameworks the way to test repositories is often to create the database with an in-memory database in the first step of the test and add objects using the DAL-framework to the in-memory database. After this, you can use the repository on the in-memory database to test if the methods work. These tests are slower, but very valid and drive your tests. It does require some cooperation from your DAL-framework.

Option 3: Test on an actual database

Another approach is to test on an actual database and isolate the unittest. You can do this in several ways: surround your tests with a transaction, clean up manually (would not recommend as very hard to maintain), completely rebuild the database after each step... Depending on the application you are building this may or may not be feasible. In my applications I can completely build a local development database from source control and my unittests on repositories use transactions to fully isolate the tests from each other (open transaction, insert data, test repository, rollback transaction).  Every build first sets up the local development database and then performs transaction-isolated unittests for the repositories on that local development database. It's a little slower then a pure Unittest but the tests are extremely valuable and catch a lot of issues.

Don't test the DAL

If you are using a DAL framework such as NHibernate, avoid the need to test that framework. You could test your mapping files by saving, retrieving and then comparing a domain object to make sure everything is okay (be sure to disable any sort of caching) but it's not as required as a lot of other tests you should be writing. I tend to do this mostly for collections on parents with conditions on the children.

When testing the return of your repositories you could simply check to see if some identifying property on your domain object matches. This can be an id but in tests it's often more beneficial to check a human readable property. In the 'get me all the cars made after 2010....' this could simply check that five cars are returned and the license plates are 'insert list here'. Added benefit is that it forces you to think about sorting AND your test automatically forces the sorting. You'd be surprised how many applications either sort multiple times (return sorted from the database, sort before creating a view object and then sort the view object, all on the same property just in case) or implicitly assume the repository sorts and accidentally remove that somehwere along the way, breaking the UI.

'Unit test' is just a name

In my opinion, unit tests should mostly not hit the database. You build an application so that every piece of code that needs data from a source does this with a repository, and that repository is injected as a dependency. This allows for easy mocking and all the TDD-goodness you want. But in the end you want to make sure that your repositories perform their duties and if the easiest way to do that is hit a database, well, so be it. I've long let go of the notion that 'unit tests should not touch the database' and learned that there are very real reasons to do this. But only if you can do this automatically and repeatedly. And weather we call such a test a 'unit test' or an 'integration test' is moot.


问:
Why is C still in the category of High Level Language?
Many of the textbooks on the C programming language tell that C is a high-level programming language, but many of the tutors online say that C is also a middle-level programming language. Why is it like that?</p>

答:
It is a higher level language than machine code (assembly), which is the point of view that C programming books and tutorials come from.

In that respect it is a high level programming language.

However, it is still very close to the hardware - much more so than other, more modern languages (Java, C# and such) - when viewed from this point of view, it is a middle level programming language.


答:
Historically, everything that abstracts over assembly code was called high-level. C certainly does that. This definition is also relatively clear-cut, in contrast to what follows.

Over time, we created more and more programming languages and invented more and more abstractions and tools. Compared to, say, Python, the C language is positively primitive in semantic richness and level of abstraction over the hardware. With that in mind, many people find it misleading to call C high-level, when there is a wealth of languages that are far higher above the hardware.

So now "high-level" usually means "abstracts a lot over hardware" and "low-level" means "abstracts little". This is the definition your tutors use.
Not everyone agrees though, and old texts don't magically adopt the new terminology, so you still see the old use of "high-level" (under which C is high-level) floating around. Keep in mind that many good C books are basically newer editions of books released twenty years ago.

Title: Why is C still in the category of High Level Language?

Body: Many of the textbooks on the C programming language tell that C is a high-level programming language, but many of the tutors online say that C is also a middle-level programming language. Why is it like that?</p>


问:
How do you explain the source of an identifed problem without making it an "excuse"?
As practicing (as much as I can at least) "egoless programming", I'm focused on solving problems whoever wrote the code related (if that person don't make dangerous code) and I like to understand the problem fully to be sure to solve the source of this problem.

However, when someone point my code to show an error, I often try to remember what was my mindset while writing the defect code and I try to explain it to the guy pointing the error to make clear what was the error source (for example when some names are badly choosen, you might use them in a way they were not intended too and with apparent success...).

Now, I do this by reflex and most of my coworkers does understand this reflex. But I also worked in companies where coworkers were in a mentality of blaming the people that made the identified problems, with or without humour (for me it have the same not-sane effect anyway).

In this kind of environnement, explaining why you got to write wrong code makes others think that you're trying to build an excuse. I remarked that most non-technical people (or non domain-expert, not sure, it's only personal experience) also react exactly like that when you try to explain why you did something wrong.

So, when dealing with this kind of people/environnement, how do you manage to explain the real source of the error without looking like "making an excuse"? (and is it even worth trying to explain?)

答:
I think it's just a matter of making your words match what you are feeling inside, and putting the thing you feel most strongly (egoless problem solving) first in your response. When a coworker points out a terrible variable name, you could say "I was really tired that day," or you could say "You're right, that is a terrible name; I was really tired that day." or "I am the one who did that; I was really tired that day." or "Thanks for finding that for me; I was really tired that day." Etc. If you lead with the reason, it sounds like an excuse. If you lead with owning the mistake, thanking someone for finding it, or just agreeing with them, the reason doesn't sound like an excuse so much.

As a bonus, when you practise this, you will almost certainly find less need to offer the explanation for those "I was tired, I didn't think anyone would use it for that, I was in a hurry" situations. You can still use it for "well sales never mentioned that they told the user that feature would be added, Bob didn't explain that to me properly, if Joe chose a better variable name I would have got it right, it worked until you changed the spec" situations, when root cause and underlying change analysis may be needed.


问:
Is it OK to use the MIT license for a project that uses Qt?
I built a Qt application. Am I allowed to LICENSE it under the MIT license?

Qt is a cross-platform application and UI framework for developers using C++ or QML, a CSS & JavaScript like language. Qt Creator is the supporting Qt IDE. Qt Cloud Services provides connected application backend features to Qt applications.

Qt, Qt Quick and the supporting tools are developed as an open source project governed by an inclusive meritocratic model. Qt can be used under open source (GPL v3 and LGPL v2.1) or commercial terms.

http://qt-project.org/

Since Qt is licensed under LGPL v2.1, I guess the answer is Yes, it's fine to use the MIT license on my non-commercial app.

The LICENSING page is too complicated for me.

So, is there any problem if I licensed my app under the MIT license?

答:
No, there is no problem.

From the LGPL:

A “Combined Work” is a work produced by combining or linking an
  Application with the Library.

Also (emphasis added):

You may convey a Combined Work under terms of your choice that, taken
  together, effectively do not restrict modification of the portions of
  the Library contained in the Combined Work and reverse engineering for
  debugging such modifications, if you also do each of the following:

It then goes on to provide a short list of things you must do such as including the LGPL license with your software, display a notice in your software that it uses an LGPL library, etc. For more information, see section 4 of the LGPL license.


问:
What is the correct Object Design/Architecture for the following scenario?
I am developing some custom controls in an Object Oriented language (using Swift/Cocoa but this is a technology agnostic question). In particular, I have a horizontal and vertical set of buttons that behave very similarly except for the fact that one is oriented vertically and the other horizontally.

My question: what is the correct way to structure these two 'things' in my project:

Should I have a (abstract) parent class that has common functionality and then two derived concrete classes for the specifics needed for horizontal-ness vs vertical-ness. This feels the most correct but given that the object is composed of other objects you are then going to have proliferated throughout the view hierarchy going downwards.

Alternately, should I design one highly generalised class that has a property for orientation and then a lot of if/switch logic in the code to drive behaviour based on this. This feels like a code-smell.

Just go and create two separate similar but technically unrelated classes and just do a little more repeated typing. Since so many things are driven by the orientation this almost seems simpler than 1 above.

Or is there another alternative?

Other canonical examples where this would arise could be horizontal vs vertical:
    - scrollers
    - stacking panels

To attempt to clarify on regarding design goals and requirements, I would like the question answered in terms of how Apple Software Architects might have approached the NSScrollView class (or how any large organization might approach similar UI library code with "mirror" horizontal and vertical components).

The answer impacts several related vertical vs horizontal classes that aggregate these buttons into rows and columns respectively as the rows and columns themselves are also very similar save for the vertical vs horizontal orientation.

答:
As a note up front, I am not familiar with how the Apple UI components commonly work and I mostly have experience working with Qt. This might influence the applicability of my answer.

I would start with a set of widgets that are orientation-neutral, but that can naturally be used where you expect an orientation-specific widget. For example a button where both dimensions can be set as fixed size or stretching and a grid with multiple rows and columns. These are concrete classes that can be used as-is.

With these orientation-agnostic widgets, a vertical button is just a button with a (relatively small) fixed-size width. And a row is just a grid with only one row.

How to realize this depends mostly on how the UI is typically being built.

If the UI is mostly coded by hand, you can create orientation-specific derived classes that do nothing more than set the appropriate defaults of their orientation-agnostic base classes. A VerticalButton class would only have a constructor to set the button's width as a fixed value.

This doesn't prevent someone from changing the width back to being variable, but that would be their own fault.

If the UI is mostly generated from a graphical designer, I would look into the possibility of having the designer provide the widgets in multiple tastes (horizontal, vertical and orientation-agnostic) that instantiate each the same class with different settings.

If that fails, I can always fall back to the first option.

Only if the orientation-specific widget needs behaviour that can't be provided by the orientation-agnostic variant would I consider making a full-fledged class (with more than a constructor) for the orientation-specific widget.

For example, if the text on a vertical button needs to be rotated, but the regular button class doesn't support text rotation.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
Q: "See this word here, how do I know if before that I should write 'a' or 'an'?"
A: Use "an" if the next word starts with a vowel
Q: "What's a vowel?"</p>

OwnerDisplayName: Matt