问:
Is the 'application code' supposed to go in the Class or somewhere else?
I am trying to teach myself programming, but I have always been very confused by the object oriented approach.

Recently, I have been reading about SOLID development principles.

When I create Classes, using Python, it seems I add the application logic there. However, this appears to defy the single responsibility principle, and injection principles.

For a simple example of my problem, let's assume that my ultimate goal is to change the TV to channel 10, turn the connected (but separate) surround sound system to max, and then turn the TV off.

I would do something like this:

```<code>from SpeakerSystem import DolbyDigital

Class Tv(object):

def __init__(self):
    self.speakers = DolbyDigital()
    self.volume = 10
    self.channel = 1
    self.power = 'Off'

def turnOn(self):
    self.power = 'On'

def turnOff(self):
    self.power = 'Off'

def channelUp(self):
    self.channel += 1

def channelDown(self):
    self.channel -= 1

def volumeUp(self):
    self.speakers.volumeUp()

def volumeDown(self):
    self.speakers.volumeDown()

def setChannel(self, station):
    self.channel = station

def process(self):
    self.channel = 10
    while self.volume != self.max_volume:
        self.volumeUp()
    self.turnOff()
</code>```

Ignore for a minute that this is a contrived example!

Then, to solve my problem i will simply instantiate Tv, and run process().

The problem is that I always create many methods like process() here; I essentially bake in my application code in with the class.

I think this is wrong? The vast majority of methods in my class actually go about solving my problem directly; they clearly will not be useful to anyone, or even myself, outside of my specific problem domain.

In the example, process is not useful to anyone (only useful for my niche problem). Imagine 10 more methods like that, which are totally useless.

Also, I have read that baking in self.speakers = DolbyDigital() is also bad design, because now Tv depends on it. And this gets messy when unit-testing; having to constantly mock out other objects. Many books suggest that objects should not even be responsible for initializing other objects....

The more I read about OOP and OODesign, it seems the class itself should be general, it should provide only the basic methods (it shouldn't actually do the whole job), and that the application code should somehow be separate. Is this true? If so, where should the application code go?

I thought about creating a plain old main() file, however it seems that if I did that, the programming paradigm then shifts to procedural. And the whole point of learning OOP is to stick with OOP!?

I am truly utterly confused about it. Again, sorry for the seemingly dumb question, but I have no formal training, so just trying to improve with your help!

I have read several object oriented books, including those by Gamma et. al, Uncle Bob, and several other seminal books. It seems my question is so stupid/novice that they do not actually cover it.

答:
You process method is indeed in a wrong place.

What is the context where you will switch to channel 10? Why channel 10, and not channel 9?

Maybe the user asked specifically the channel 10. In this case, 10 should be the input, not a value within the class.

Maybe this is the default channel, the one which will be shown every time the TV is turned on. In this case, this should be either a constant or, often, a configuration entry.

By making it a constant, you can be sure that later, when requirements change and the default channel becomes the channel 9, you have to make the change in one location only.

By moving it to configuration, you acquire the benefit of letting the system administrator change the value later, without having to modify and redeploy the application.

As for the self.speakers = DolbyDigital() part, you should let the caller the ability to set the speakers. This is useful in two cases:

When the caller doesn't want to use DolbyDigital, but wants to use something else.

When you are testing your class. You can then set the speakers to SpeakersMock or SpeakersStub in order to focus your testing on the class itself and isolate those tests to avoid side effects.

This doesn't prevent you from having a default value for speakers field. The benefit of having one is when you initialize Tv in different places in your code. Instead of having to think every time about the initialization of speakers, you just let the class apply the default value.

The lack of such default values can sometimes lead to constructors requesting a dozen of parameters. Not inherently bad, but still difficult to use.


问:
I have a particular coding style, does it have a name?
I don't know if it is just what my first Java lecturer taught me or if it is based on something. It has parts of it that are the same as the Oracle Java style (naming) but differs in other ways, as they seems to prefer K&R braces.

Braces are always on a line of their own.

Even one line statements inside blocks get braces.

Spaces after the comma separating parameters.

Spaces between the operator and the variables for binary operators but not for unary operators.

Four spaces for a tab.

Blank lines between separate concepts inside functions and between class level elements i.e. separating functions from each other and from declarations/definitions.

Capital for each new word.

Classes start with a capital.

Functions and variables start with a lower case letter.

Constants are all capitals.

```<code>public class MyClass
{
    public static final float PI = 3.14;

    public static void main(String[] args)
    {
        if((1 + 2) == 3 && returnFirstMinusSecond(9, 2) == 7 && !returnsFalse())
        {
            // output
            System.out.println("true");

            // some other code that is logically separate from output
            // do something else that I want to keep separate as it is complex
        }
        else
        {
            while(true)
            {
                System.out.println("false");
            }
        }
    }
}
</code>```

答:
Coding styles generally aren't referred to by name unless the name is a clear reference to a published style guide, such as the ones published by Google.

Indeed, rarely is the collective styles of indentation, naming convention, alignment, etc. given a single name, and even those individual styles don't have standard names.

Based on your description, however, I can give you the names that are commonly-accepted by parts of the programming community:

Your indentation style is usually called Allman Style, for Eric Allman, the author of sendmail and syslog.

Your naming convention is generally referred to as CamelCase, in reference to the bumpy use of upper- and lower-case letters. More specifically, you are mixing UpperCamelCase (also sometimes called PascalCase) for class names and lowerCamelCase for method names.

Other than that, there isn't really an applicable name for operator style or alignment of which I am aware.

Your use of internal whitespace (such as between operators and in parameter lists and between logical blocks), however, is widely regarded as simply "good style."

ContentLicense: CC BY-SA 3.0


问:
Should HTTP Request/Response objects be immutable?
I think it's safe to say that most web applications are based on the request/response paradigm.  PHP has never had a formal abstraction of these objects.  One group is trying to change this: https://github.com/php-fig/fig-standards/blob/master/proposed/http-message.md

However, they sort of got side tracked on the issue of immutability. On the one hand, request/response object generally need very little change during their life cycle.  On the other hand, the response object in particular often needs HTTP headers to be added.

Furthermore, immutability has never really caught on in the land of PHP.

What advantages do people see in using immutable request/response objects?

Let's suppose you are returning a json object.

```<code>$response = new JsonResponse($item);
</code>```

Nice and simple.  But it turns out that the request was a Cross-Origin Resource Sharing(CORS) request.  The code that generates the response should not care but somewhere downstream is a process that will add the necessary Access-Control headers.  Any advantage to keeping the original response and creating a new one with the additional headers?  Or is it strictly a question of programming style.

The request object is a bit more interesting.  It starts off the same:

```<code>$request = new Request('incoming request information including uri and headers');
</code>```

The initial information should not need to be changed.  However, as the request get's passed along there is often a need to add additional processing information.  For example, you may have a url matcher which decides what action should be executed for a given request.

```<code>$request->setAttribute('action',function() {});
</code>```

Actually executing the action is the responsibility of a down stream process.  You could have a mutable RequestAttributesCollection which wraps the immutable request but that tends to be a bit awkward in practice.  You could also have a request that's immutable except for an attributes collection.  Exceptions tends to be awkward as well.  Any experience on dealing with these sorts of requirements?

答:
Immutable objects in general have several benefits.

The most important one is how easy is to use immutable objects in code executed in parallel. This also explains why "immutability has never really caught on in the land of PHP".

State consistency is easier to obtain.

Objects are easy, more natural to work with.

The essential thing is how much the object should change during its life time—every change to an immutable object requires to create an additional instance, which can quickly be too expensive in terms of memory (and probably CPU cycles as well). This is also why most programming languages where string is immutable ends up having another class for some sort of mutable strings, such as StringBuilder in C#, to respond to situations where strings are concatenated from many small parts, each part added dynamically.

In a client-side library (sending an HTTP request and receiving a response), it makes sense to make HTTP request and response immutable: while some requests could be build with a fluent interface, this is not the major usage. The response won't be changed anyway, so immutability makes sense.

In a server-side library (receiving an HTTP request and sending a response), while the request can be immutable, I'm not sure if the response can be. The data itself can be a stream (which, for some people—see below—forces the response object to be mutable), and the headers themselves can be added "on the fly" during the execution of the script, until the response starts to be sent to the client.

In both cases, given that there is no execution in parallel, I'm not sure if the slight benefit of readability compensates the possible lack of flexibility.

Make sure you also read a more complete article by Evert Pot about PSR-7. The article explains, among others, than one of the cases where such immutability is problematic is for long responses which should be streamed. Personally, I don't see the point: IMHO, nothing forbids an immutable object to contain a stream (for instance, a FileReader object can be immutable even if it reads a file which can change over time). Python's Flask framework uses a different approach when it comes to large responses (or responses which take time to generate) by returning an iterator.


问:
How can I approach creating an efficient algorithm for maximizing value with these specific constraints?
I'm having trouble coming up with an approach that isn't n^2 for this problem. Here's a contrived, simplified version I've come up with:

Let's say you're a company that needs 4 employees to launch in a new city, a manager, two salespeople, and a customer support rep, and you magically know how much impact every candidate will have and how much salary they require to take the job. Your table of potential employees looks something like this:

```<code>Name           Position       Salary     Impact
Adam Smith     Manager        60,000     11
Allison Brown  Salesperson    40,000     9
Brad Stewart   Manager        55,000     9
...etc (thousands of records)
</code>```

What algorithmic approach can be taken to find the maximum "impact" while still filling all the positions and remaining under, say, a 200,000 budget?

Thanks!

答:
I'd use Integer Linear Programming (which, in essence, is constraint programming, which is what you are doing) to solve this kind of problem, using CPLEX in conjunction with Visual Studio. As stated in your post, the objective of your program will be to maximize a goal given a set of constraints (e.g. total budget must be less than $200,000). </p>

<p>To get started and if you have not previously configured CPLEX to work with Visual Studio, consult this guide. For a template of problems that need to maximize a goal, check the following tutorial handout that contains code samples that you can modify to your criteria. </p>

Body:
I'd use Integer Linear Programming (which, in essence, is constraint programming, which is what you are doing) to solve this kind of problem, using CPLEX in conjunction with Visual Studio. As stated in your post, the objective of your program will be to maximize a goal given a set of constraints (e.g. total budget must be less than $200,000).

To get started and if you have not previously configured CPLEX to work with Visual Studio, consult this guide. For a template of problems that need to maximize a goal, check the following tutorial handout that contains code samples that you can modify to your criteria.


问:
Architecture for web and mobile clients
The application that I work on needs to have a web interface (ASP.NET MVC) and mobile interfaces (Android/IPhone native). The features for mobile applications and web application might not overlap (some features are similar, some are different)

At the moment, I'm thinking of 2 ways to structure the applications like below:

For the top approach, just need one web server that server both web and mobile clients. Mobile will communicate with server through Json (serialized by ASP.NET MVC). The service layer is just a plain class library to be referenced by web layer

Pros

Faster, since there's no cross-machine communication between web and
service layer

Simpler

Cons

Security? Any security concern here?

Less flexible when scaling (can only scale both web and service layer as one unit).

For the bottom approach, need one web server and one application server (for WCF/Web API). Mobile will communicate directly with application server through Json

Pros

Can secure web and application servers separately, extra layer of protection on application layer. But the application server is exposed to mobile anyway right?

Can scale web and application servers independently

Cons

Slower

More complicated due to WCF/Web API in the middle

It's the first time I do the application for both web and mobile like this. Which approach is commonly used in this scenario? User tends to favor bottom approach, but I think in this case it might be overkill to follow bottom approach

答:
The main problem that I see is that with the top approach, your website needs to be able to accept requests from mobile, as opposed to the services. That seems like something the website should not have to worry about. In particular, it implies either your website has a bunch of "pass-through" logic to duplicate the API of the services, or the website is providing a different API from that of the services (probably a little of both). Either way, that's a huge maintainability problem. Plus, it adds one extra hurdle (and potential bottleneck) for mobile requests to jump through, compared to talking to the services directly.

The claims about needing one or two servers in each case are really an orthogonal issue: You can put the website and its services on the same server if you want (I've done this many times at my job). Whether you do that or not doesn't have much to do with whether or not the mobile client is talking to your web page or your services. I would expect this decision has more to do with (as you pointed out) security or complexity, or perhaps with scalability (ie whether the bottlenecks are in your services or your website). But for a sufficiently large/complex/important website, I believe these factors would all lean towards using separate machines.

Therefore, I would recommend the bottom approach.

Title: Architecture for web and mobile clients


问:
Different Implemenations of Tail Call Optimisation
I've heard some people in my university discuss the tail call optimisation in ML as if it were a special version tail call optimisation.
Does the ML (SML/F#) implementations of tco in these languages differ substantially from the implementation in other languages, such as C++ and Haskell?</p>

答:
Does the ML (SML/F#) implementations of tco in these languages differ substantially from the implementation in other languages, such as C++ and Haskell?

Not as far as I know, no. The optimization of discarding the existing stack rather than saving off its current state (and possibly adjusting the execution pointer directly) on the last function call in the current stack is common across languages. There may be details, like since Haskell works lazily it might need additional steps, but the implementations do not differ substantially since the underlying assembly does not differ at all.

The difference is the level of guarantee provided by the language specification and/or the language implementation. For functional languages, there is very often a stronger guarantee (will always provide TCO, will provide TCO in cases of mutual recursion), since having an ever growing stack for certain common structures would make that language/implementation effectively useless. Non-functional languages often make no guarantee, or some weak guarantee (may supply TCO if we feel like it) since there are common alternatives that do not grow the stack.


问:
Where should I place a typedef when used in method signatures in C++?
I'm using an Optional class quite similar to that of boost. For semantic reasons, I switched an attribute of the same (structured) type in some class definitions (and therefore also in method signatures) from mandatory to optional. So, in each related class header file, I included the header with the definition of Optional and also a typedef to ease typing (see CHANGE comments); the passages read like this:

```<code>#include <MyAttrType.h>
#include <Optional.h>                          // CHANGE
typedef Optional<MyAttrType> OptionalAttrType; // CHANGE

class MyClassX
{
// ...
</code>```

Today I run Cppcheck 1.68 on the project and got this style warning:

The typedef 'OptionalAttrType' hides a typedef with the same name.

How can I get rid of theses style warnings without making something bad?

Remarks:

MyAttrType itself is currently independent from Optional (because defined early in the project history, while Optional was being last time)

I think of introducing a new header only for this purpose. But maybe there are better options?

I guess that it could generally be an indication of bad design, to have many classes with the same optional attribute, but I'm not sure in my special case. The code is currently changing to reach higher prioritized goals.

of course, MyAttrType, OptionalAttrType, and MyClassX aren't the actual names

答:
I typically use one of the two ways.

First way is to typedef at the place-of-first-declaration.

Second way is to typedef at each place-of-use, and make it only visible to that place-of-use (by putting it inside the class or method that uses it).

(1) Put the typedef close to the type that is being wrapped.

```<code>/* MyAttrType.h */

#include <Optional.h>

// README : See Optional<MyAttrType> at the end of this header

struct MyAttrType
{
    // ....
};

// (put the typedef here)
typedef Optional<MyAttrType> OptionalMyAttrType;

/* ---------------------------- */
/* Every other C++ source files */
#include "MyAttrType.h"

// .... Any code can use OptionalMyAttrType there.
</code>```

(2) Make the typedef visible only to each class that uses it.

```<code>/* MyAttrType.h */

namespace my_pod_types
{
    struct MyAttrType { /* ... */ };
}

// (nothing else outside.)

/* ---------------------------- */
/* Every other C++ source files */

#include "MyAttrType.h"
#include "Optional.h"

class MyClassX
{
private:
    typedef Optional<my_pod_types::MyAttrType> OptionalMyAttrType;
public:
    // ...
private:
    OptionalMyAttrType m_optAttr;
};
</code>```

Most of the time, the template relevant to me is either std::unique_ptr and std::shared_ptr. Furthermore, I will just decide that a class will either use one way or the other, and then typedef that smart pointer wrapper as "MyClassOnePtr". Draconian, but a library's main author is supposed to know what is the best for the library most of the time.

If it is not obvious which one of the two smart pointers should be preferred, then I will not put the typedef in the first header (so, I won't use option #1 unless the choice is obvious.)

Most of the time, you will realize that option #2 does not always shield the use of Optional<T> from the end-user. That is, the application logic may require users of MyClassX to deal with Optional<T> when interacting with it. When that happens, you can't hide it anymore. It is not an implementation detail; it is part of the visible surface.

Finally, you should be aware of the C++ limitation to forward-declare things. Namely, there are times where C++ needs to know up-front:

Size of the type being wrapped;

Existence of a default constructor and destructor;

And so on.

See this question on Stackoverflow (about unique::ptr) for examples of such limitations.

Another unrelated thing I would like to share, after reading ixrec's answer.

I started following a "nothing in the default namespace" policy after finding that you can't get Doxygen (a widely used C++ documentation to HTML generator) to generate well-organized documentation unless you categorize your classes by using namespaces. It seems it doesn't matter how you name those namespaces; as long as Doxygen sees them as distinct, and human users don't complain about it, any namespacing approach will be fine.

ContentLicense: CC BY-SA 4.0

Body:
I typically use one of the two ways.

First way is to typedef at the place-of-first-declaration.

Second way is to typedef at each place-of-use, and make it only visible to that place-of-use (by putting it inside the class or method that uses it).

(1) Put the typedef close to the type that is being wrapped.

/* MyAttrType.h */

#include <Optional.h>

// README : See Optional<MyAttrType> at the end of this header

struct MyAttrType
{
    // ....
};

// (put the typedef here)
typedef Optional<MyAttrType> OptionalMyAttrType;

/* ---------------------------- */
/* Every other C++ source files */
#include "MyAttrType.h"

// .... Any code can use OptionalMyAttrType there.

(2) Make the typedef visible only to each class that uses it.

/* MyAttrType.h */

namespace my_pod_types
{
    struct MyAttrType { /* ... */ };
}

// (nothing else outside.)

/* ---------------------------- */
/* Every other C++ source files */

#include "MyAttrType.h"
#include "Optional.h"

class MyClassX
{
private:
    typedef Optional<my_pod_types::MyAttrType> OptionalMyAttrType;
public:
    // ...
private:
    OptionalMyAttrType m_optAttr;
};

Most of the time, the template relevant to me is either std::unique_ptr and std::shared_ptr. Furthermore, I will just decide that a class will either use one way or the other, and then typedef that smart pointer wrapper as "MyClassOnePtr". Draconian, but a library's main author is supposed to know what is the best for the library most of the time.

If it is not obvious which one of the two smart pointers should be preferred, then I will not put the typedef in the first header (so, I won't use option #1 unless the choice is obvious.)

Most of the time, you will realize that option #2 does not always shield the use of Optional<T> from the end-user. That is, the application logic may require users of MyClassX to deal with Optional<T> when interacting with it. When that happens, you can't hide it anymore. It is not an implementation detail; it is part of the visible surface.

Finally, you should be aware of the C++ limitation to forward-declare things. Namely, there are times where C++ needs to know up-front:

Size of the type being wrapped;

Existence of a default constructor and destructor;

And so on.

See this question on Stackoverflow (about unique::ptr) for examples of such limitations.

Another unrelated thing I would like to share, after reading ixrec's answer.

I started following a "nothing in the default namespace" policy after finding that you can't get Doxygen (a widely used C++ documentation to HTML generator) to generate well-organized documentation unless you categorize your classes by using namespaces. It seems it doesn't matter how you name those namespaces; as long as Doxygen sees them as distinct, and human users don't complain about it, any namespacing approach will be fine.


问:
Property based testing without reimplementing the code under test
Given a very simple method such as:

```<code>  def squaredDistance(p1: Point, p2: Point) =
    math.pow(p1.lon - p2.lon, 2.0) + math.pow(p1.lat - p2.lat, 2.0)
</code>```

What are some valuable property-based tests that don't simply reimplement the method?

I can only think of testing for result >= 0.0, which is pretty broad.

答:
Short answer: test against hard-coded expected outputs.

Long answer:

You should be able to tell what is the expected output from a given input, by following the logic in your head or on paper, before implementing. Take the inputs and the outputs and turn them into tests, one by one, coding the algorithm little by little.

However, like in your example (squareDistance), the "little by little" part may feel too dogmatic, and it does so because the tests are not giving you any feedback if you already know exactly what code you need to write. So in these cases, I'd suggest to implement the code directly, then run it against a few inputs to get the outputs, check if they are correct manually, and then create tests where the inputs and outputs are hard-coded.

So, regardless of whether the tests come first or after, you should not duplicate the logic within the tests - keep only the inputs and their respective expected results.


答:
There are three errors:

Your headers declare a name in a namespace not private to your library which they have no business declaring.

You seem to not make sure there's only one definition of it in your whole library.

You are trying to shut the warning up instead of correcting that bug.

What you should do is one of:

Make it a part of your interface.

Or hide it in your libraries namespace (probably in a nested namespace internal or such).

Or remove it completely and writing the full names.

In case you choose option 1 or 2, make sure it's only defined in exactly one place.

Title: Where should I place a typedef when used in method signatures in C++?

Body:
I'm using an Optional class quite similar to that of boost. For semantic reasons, I switched an attribute of the same (structured) type in some class definitions (and therefore also in method signatures) from mandatory to optional. So, in each related class header file, I included the header with the definition of Optional and also a typedef to ease typing (see CHANGE comments); the passages read like this:

```<code>#include <MyAttrType.h>
#include <Optional.h>                          // CHANGE
typedef Optional<MyAttrType> OptionalAttrType; // CHANGE

class MyClassX
{
// ...
</code>```

Today I run Cppcheck 1.68 on the project and got this style warning:

The typedef 'OptionalAttrType' hides a typedef with the same name.

How can I get rid of theses style warnings without making something bad?

Remarks:

MyAttrType itself is currently independent from Optional (because defined early in the project history, while Optional was being last time)

I think of introducing a new header only for this purpose. But maybe there are better options?

I guess that it could generally be an indication of bad design, to have many classes with the same optional attribute, but I'm not sure in my special case. The code is currently changing to reach higher prioritized goals.

of course, MyAttrType, OptionalAttrType, and MyClassX aren't the actual names


问:
Can SSE (or AVX) be used to do large bsf?
I'm faced with having to do a bsf (find the first bit set) in a 512bits bitmap. This is in the hot path so I'd like to see how I can speed things up.

Right now I'm maintaining a header entry to know in which 32bits block the first set bit will be found. By doing a bsf on the header + a bsf in the entry designed by the header and some arithmetic, one can can compute the bsf of the whole bitmap fairly fast.

But this obvious require to maintain the header in addition of the bitmap itself. I'd like to explore alternative. Notably, SSE or AVX, but failed to come up with a solution.

Is that possible at all ? If yes, how ?

答:
Ok if nobody else wants to, I'll have a hack at it, assuming avx2 available (untested because avx2 isn't for me). No idea if this is actually faster than just plowing through 8 iterations of bsf on a 64 bit integer register. I have my doubts. Assume src_address holds the most significant bit. src_address + 511 holds the least.

bsf finds the least significant 1 bit.

We can isolate the least significant 1 bit with the formula

```<code>x & (-1) //Hackers Delight 1st ed p11
</code>```

avx2 uses 256 bit registers so we'll have to unroll to get through all 512 bits.

int BSR512(char* src_address) {
    // load the data into 2 registers
    __m256i data1 = _mm256_loadu_si256((__m256i*)src_address);
    __m256i data2 = _mm256_loadu_si256((__m256i*)(src_address + 256));

    // zero a register for negate and comparison
    //__m256i zeroes = _mm256_set_epi32(0,0,0,0,0,0,0,0); //NO
    __m256i _mm256_setzero_si256();

    // negate
    __m256i negs1 = _mm256_sub_epi32(zeroes, data1);
    __m256i negs2 = _mm256_sub_epi32(zeroes, data2);
    // x & (-x)

    // these should be _mm256_and_si256 to avoid casts -thanks rwong
    __m256i lsbs1 = _mm256_castps_si256(_mm256_and_ps(_mm256_castsi256_ps(data1), _mm256_castsi256_ps(negs1)));
    __m256i lsbs2 = _mm256_castps_si256(_mm256_and_ps(_mm256_castsi256_ps(data2), _mm256_castsi256_ps(negs2)));

    // set int32 in a reg to all 1s if we found something
    __m256i mask1 = _mm256_cmpeq_epi32(lsbs1, zeroes);
    __m256i mask2 = _mm256_cmpeq_epi32(lsbs2, zeroes);

    // which of the packed ints was set to all 1s? put in a normal register
    int which1 = _mm256_movemask_ps (_mm256_castsi256_ps(mask1));

    // isolate the lowest set bit
    which1 = (which1 & -which1);
    int which2 = _mm256_movemask_ps (_mm256_castsi256_ps(mask2));
    which2 = (which2 & -which2);

    // do you have to do a dance here? Does the lowest memory address contain
    // the highest bit or the lowest bit - ask your data and change this
    if (which1 != 0) {
        // extract the 32 bit int with the bit set
        const char w = which1;
        int contains_set_bit = _mm256_extract_epi32(lsbs1, w);

        // add number of bits in lower integers unset to bsf
        return which1 * 32 + BSF(contains_set_bit);

    } else if (which2 != 0) {
        // as above but didn't find in the first loop
        const char w = which2;
        int contains_set_bit _mm256_extract_epi32(lsbs2, w);

        return which2 * 32 + BSF(contains_set_bit) + 256;
    }
    return 0;
 }
```
<p>Which compiled with <code>clang++ -std=c++11 -Wall -g -march=core-avx2 -O3</code></p>
<p><code>objdump -DC a.out</code> gives:</p>
```0000000000400a90 <BSF512(char*)>:
  400a90:       c5 fe 6f 07             vmovdqu (%rdi),%ymm0
  400a94:       c5 f5 ef c9             vpxor  %ymm1,%ymm1,%ymm1
  400a98:       c5 f5 fa d0             vpsubd %ymm0,%ymm1,%ymm2
  400a9c:       c5 fd db c2             vpand  %ymm2,%ymm0,%ymm0
  400aa0:       c5 fd 76 d1             vpcmpeqd %ymm1,%ymm0,%ymm2
  400aa4:       c5 fc 50 c2             vmovmskps %ymm2,%eax
  400aa8:       c4 e2 70 f3 d8          blsi   %eax,%ecx
  400aad:       74 26                   je     400ad5 <BSF512(char*)+0x45>
  400aaf:       89 c8                   mov    %ecx,%eax
  400ab1:       83 e0 07                and    $0x7,%eax
  400ab4:       c5 f9 6e c8             vmovd  %eax,%xmm1
  400ab8:       c4 e2 75 36 c0          vpermd %ymm0,%ymm1,%ymm0
  400abd:       c5 f9 7e c2             vmovd  %xmm0,%edx
  400ac1:       c1 e1 05                shl    $0x5,%ecx
  400ac4:       f3 0f bc c2             tzcnt  %edx,%eax
  400ac8:       ff c0                   inc    %eax
  400aca:       85 d2                   test   %edx,%edx
  400acc:       0f 44 c2                cmove  %edx,%eax
  400acf:       01 c8                   add    %ecx,%eax
  400ad1:       c5 f8 77                vzeroupper
  400ad4:       c3                      retq
  400ad5:       c5 fe 6f 87 00 01 00    vmovdqu 0x100(%rdi),%ymm0
  400adc:       00
  400add:       c5 f5 fa d0             vpsubd %ymm0,%ymm1,%ymm2
  400ae1:       c5 fd db c2             vpand  %ymm2,%ymm0,%ymm0
  400ae5:       c5 fd 76 c9             vpcmpeqd %ymm1,%ymm0,%ymm1
  400ae9:       c5 fc 50 c9             vmovmskps %ymm1,%ecx
  400aed:       31 c0                   xor    %eax,%eax
  400aef:       c4 e2 70 f3 d9          blsi   %ecx,%ecx
  400af4:       74 27                   je     400b1d <BSF512(char*)+0x8d>
  400af6:       89 c8                   mov    %ecx,%eax
  400af8:       83 e0 07                and    $0x7,%eax
  400afb:       c5 f9 6e c8             vmovd  %eax,%xmm1
  400aff:       c4 e2 75 36 c0          vpermd %ymm0,%ymm1,%ymm0
  400b04:       c5 f9 7e c0             vmovd  %xmm0,%eax
  400b08:       c1 e1 05                shl    $0x5,%ecx
  400b0b:       f3 0f bc d0             tzcnt  %eax,%edx
  400b0f:       ff c2                   inc    %edx
  400b11:       85 c0                   test   %eax,%eax
  400b13:       0f 44 d0                cmove  %eax,%edx
  400b16:       8d 84 11 00 01 00 00    lea    0x100(%rcx,%rdx,1),%eax
  400b1d:       c5 f8 77                vzeroupper
  400b20:       c3                      retq
  400b21:       66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
  400b28:       00 00 00
  400b2b:       0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)
```

Body:
Ok if nobody else wants to, I'll have a hack at it, assuming avx2 available (untested because avx2 isn't for me). No idea if this is actually faster than just plowing through 8 iterations of bsf on a 64 bit integer register. I have my doubts. Assume src_address holds the most significant bit. src_address + 511 holds the least.

bsf finds the least significant 1 bit.

We can isolate the least significant 1 bit with the formula

x & (-1) //Hackers Delight 1st ed p11

avx2 uses 256 bit registers so we'll have to unroll to get through all 512 bits.

int BSR512(char* src_address) {
    // load the data into 2 registers
    __m256i data1 = _mm256_loadu_si256((__m256i*)src_address);
    __m256i data2 = _mm256_loadu_si256((__m256i*)(src_address + 256));

    // zero a register for negate and comparison
    //__m256i zeroes = _mm256_set_epi32(0,0,0,0,0,0,0,0); //NO
    __m256i _mm256_setzero_si256();

    // negate
    __m256i negs1 = _mm256_sub_epi32(zeroes, data1);
    __m256i negs2 = _mm256_sub_epi32(zeroes, data2);
    // x & (-x)

    // these should be _mm256_and_si256 to avoid casts -thanks rwong
    __m256i lsbs1 = _mm256_castps_si256(_mm256_and_ps(_mm256_castsi256_ps(data1), _mm256_castsi256_ps(negs1)));
    __m256i lsbs2 = _mm256_castps_si256(_mm256_and_ps(_mm256_castsi256_ps(data2), _mm256_castsi256_ps(negs2)));

    // set int32 in a reg to all 1s if we found something
    __m256i mask1 = _mm256_cmpeq_epi32(lsbs1, zeroes);
    __m256i mask2 = _mm256_cmpeq_epi32(lsbs2, zeroes);

    // which of the packed ints was set to all 1s? put in a normal register
    int which1 = _mm256_movemask_ps (_mm256_castsi256_ps(mask1));

    // isolate the lowest set bit
    which1 = (which1 & -which1);
    int which2 = _mm256_movemask_ps (_mm256_castsi256_ps(mask2));
    which2 = (which2 & -which2);

    // do you have to do a dance here? Does the lowest memory address contain
    // the highest bit or the lowest bit - ask your data and change this
    if (which1 != 0) {
        // extract the 32 bit int with the bit set
        const char w = which1;
        int contains_set_bit = _mm256_extract_epi32(lsbs1, w);

        // add number of bits in lower integers unset to bsf
        return which1 * 32 + BSF(contains_set_bit);

    } else if (which2 != 0) {
        // as above but didn't find in the first loop
        const char w = which2;
        int contains_set_bit _mm256_extract_epi32(lsbs2, w);

        return which2 * 32 + BSF(contains_set_bit) + 256;
    }
    return 0;
 }

Which compiled with clang++ -std=c++11 -Wall -g -march=core-avx2 -O3

objdump -DC a.out gives:

0000000000400a90 <BSF512(char*)>:
  400a90:       c5 fe 6f 07             vmovdqu (%rdi),%ymm0
  400a94:       c5 f5 ef c9             vpxor  %ymm1,%ymm1,%ymm1
  400a98:       c5 f5 fa d0             vpsubd %ymm0,%ymm1,%ymm2
  400a9c:       c5 fd db c2             vpand  %ymm2,%ymm0,%ymm0
  400aa0:       c5 fd 76 d1             vpcmpeqd %ymm1,%ymm0,%ymm2
  400aa4:       c5 fc 50 c2             vmovmskps %ymm2,%eax
  400aa8:       c4 e2 70 f3 d8          blsi   %eax,%ecx
  400aad:       74 26                   je     400ad5 <BSF512(char*)+0x45>
  400aaf:       89 c8                   mov    %ecx,%eax
  400ab1:       83 e0 07                and    $0x7,%eax
  400ab4:       c5 f9 6e c8             vmovd  %eax,%xmm1
  400ab8:       c4 e2 75 36 c0          vpermd %ymm0,%ymm1,%ymm0
  400abd:       c5 f9 7e c2             vmovd  %xmm0,%edx
  400ac1:       c1 e1 05                shl    $0x5,%ecx
  400ac4:       f3 0f bc c2             tzcnt  %edx,%eax
  400ac8:       ff c0                   inc    %eax
  400aca:       85 d2                   test   %edx,%edx
  400acc:       0f 44 c2                cmove  %edx,%eax
  400acf:       01 c8                   add    %ecx,%eax
  400ad1:       c5 f8 77                vzeroupper
  400ad4:       c3                      retq
  400ad5:       c5 fe 6f 87 00 01 00    vmovdqu 0x100(%rdi),%ymm0
  400adc:       00
  400add:       c5 f5 fa d0             vpsubd %ymm0,%ymm1,%ymm2
  400ae1:       c5 fd db c2             vpand  %ymm2,%ymm0,%ymm0
  400ae5:       c5 fd 76 c9             vpcmpeqd %ymm1,%ymm0,%ymm1
  400ae9:       c5 fc 50 c9             vmovmskps %ymm1,%ecx
  400aed:       31 c0                   xor    %eax,%eax
  400aef:       c4 e2 70 f3 d9          blsi   %ecx,%ecx
  400af4:       74 27                   je     400b1d <BSF512(char*)+0x8d>
  400af6:       89 c8                   mov    %ecx,%eax
  400af8:       83 e0 07                and    $0x7,%eax
  400afb:       c5 f9 6e c8             vmovd  %eax,%xmm1
  400aff:       c4 e2 75 36 c0          vpermd %ymm0,%ymm1,%ymm0
  400b04:       c5 f9 7e c0             vmovd  %xmm0,%eax
  400b08:       c1 e1 05                shl    $0x5,%ecx
  400b0b:       f3 0f bc d0             tzcnt  %eax,%edx
  400b0f:       ff c2                   inc    %edx
  400b11:       85 c0                   test   %eax,%eax
  400b13:       0f 44 d0                cmove  %eax,%edx
  400b16:       8d 84 11 00 01 00 00    lea    0x100(%rcx,%rdx,1),%eax
  400b1d:       c5 f8 77                vzeroupper
  400b20:       c3                      retq
  400b21:       66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
  400b28:       00 00 00
  400b2b:       0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)


问:
When should I mix functions with data in a class?
Based on some questions I asked (1, 2,3), I am frequently suggested to separate data from functions (because of changes in function, single responsibility, separation of concerns, adopting interfaces, immutability, ...).

Then my question is: In which situation functions should be encapsulated with data? what type of functions are they? Is representing an entity or a concept a single responsibility? if yes then I may conclude no function should be introduced in a class which represents an entity! Did I miss something?

According to the following approaches, what happens if I always follow the second approach! Please note in the second approach class Entity has no private state variable as it has no function, then its fields are accessible in class EntityOp1 and EntityOp23

```<code>class Entity
{
    public data;
    private s1, s2, s3;
    operation1;
    operation2;
    operation3;
}
</code>```

vs.

```<code>class Entity
{
   public data;
}

class EntityOp1
{
     Entity e;
     private s1;
     operation1;
}
class EntityOp23
{
     Entity e;
     private s2, s3;
     operation2;
     operation3;
}
</code>```

答:
If your conclusion from previous answers is that you should separate function fron data, either

You have misunderstood the answers

Those answers are wrong.

This assumes that you are using an object oriented language, where the whole idea is to combine functions and data.


答:
The easy answer is to mix data with functions that are responsible for that data. For instance, if you have a Document class, it makes sense to have a CalculateWordCount function in it, since it's the class that's responsible for the Words inside the Document. Alternately, you can have the Document responsible for Paragraph objects, which are in turn responsible for Paragraph-level functions, and so on.

The tricky part is modelling functions that seem to span several areas of responsibility. For instance, a Save method on that Document. Is is the responsibility of the Document to save itself, even though it will now have to be aware of a filesystem on which to save? Should we instead have a FileSystem class which receives the Document class and saves it (which allows us to switch it with a WebStorage later on), or pass the FileSystem into the Document.Save? Both are valid designs, and they're where experience can help you decide.

Title: When should I mix functions with data in a class?

Body:
Based on some questions I asked (1, 2,3), I am frequently suggested to separate data from functions (because of changes in function, single responsibility, separation of concerns, adopting interfaces, immutability, ...).

Then my question is: In which situation functions should be encapsulated with data? what type of functions are they? Is representing an entity or a concept a single responsibility? if yes then I may conclude no function should be introduced in a class which represents an entity! Did I miss something?

According to the following approaches, what happens if I always follow the second approach! Please note in the second approach class Entity has no private state variable as it has no function, then its fields are accessible in class EntityOp1 and EntityOp23

```<code>class Entity
{
    public data;
    private s1, s2, s3;
    operation1;
    operation2;
    operation3;
}
</code>```

vs.

```<code>class Entity
{
   public data;
}

class EntityOp1
{
     Entity e;
     private s1;
     operation1;
}
class EntityOp23
{
     Entity e;
     private s2, s3;
     operation2;
     operation3;
}
</code>```


答:
In the end, I thought of more properties and this became quite a useful test.

The squared distance between any point and itself is 0.0

The distance between any two distinct points is > 0.0, measured from either point

For any number n, the distance between Point(0,0) and Point(n,n) is n*n*2 (this one normalises one point to see the effect on another)

Here are these properties as implemented in Scala

```<code>  def pointSelfZeroSqDist = prop { p: Point =>
    squaredDistance(p, p) mustEqual 0.0
  }

  def pointOtherPositive = prop { (p1: Point, p2: Point) =>
    (squaredDistance(p1, p2) must be_>(0.0)) and
    (squaredDistance(p2, p1) must be_>(0.0)).unless(p1 == p2)
  }

  def sameDistanceEitherWay = prop { (p1: Point, p2: Point) =>
    squaredDistance(p1, p2) mustEqual squaredDistance(p2, p1)
  }

  def fromZero = prop { n: Double =>
    squaredDistance(Point(0, 0), Point(n, n)) mustEqual n*n*2
  }
</code>```

Title: Property based testing without reimplementing the code under test

Body:
Given a very simple method such as:

```<code>  def squaredDistance(p1: Point, p2: Point) =
    math.pow(p1.lon - p2.lon, 2.0) + math.pow(p1.lat - p2.lat, 2.0)
</code>```

What are some valuable property-based tests that don't simply reimplement the method?

I can only think of testing for result >= 0.0, which is pretty broad.

Body:
In the end, I thought of more properties and this became quite a useful test.

The squared distance between any point and itself is 0.0

The distance between any two distinct points is > 0.0, measured from either point

For any number n, the distance between Point(0,0) and Point(n,n) is n*n*2 (this one normalises one point to see the effect on another)

Here are these properties as implemented in Scala

  def pointSelfZeroSqDist = prop { p: Point =>
    squaredDistance(p, p) mustEqual 0.0
  }

  def pointOtherPositive = prop { (p1: Point, p2: Point) =>
    (squaredDistance(p1, p2) must be_>(0.0)) and
    (squaredDistance(p2, p1) must be_>(0.0)).unless(p1 == p2)
  }

  def sameDistanceEitherWay = prop { (p1: Point, p2: Point) =>
    squaredDistance(p1, p2) mustEqual squaredDistance(p2, p1)
  }

  def fromZero = prop { n: Double =>
    squaredDistance(Point(0, 0), Point(n, n)) mustEqual n*n*2
  }


答:
The main purposes of OOP is to limit scope in which fields (or properties) can be mutated. This makes reasoning and debugging of said code much easier. That is why 3rd question you are referencing talks about mutability. If your fields are immutable, then there is no need to limit scope of access to field, so separating data from operations makes much more sense. That is what all pure/functional languages do.

You probably misunderstood the SRP and separation of concerns. Data and functions are NOT separate concerns. They are parts of single concern. You should always model your functions and data as interconected parts, not as separate entities.

But the problems start when you include dependencies into the mix. Thats what first two referenced questions are about. Having dependency on some other code is a liability, so you should try minimize code that depends on something else. If you have class that depends on some complex library, but only 10% of that class actually needs that library, then it is good idea to separate those 10% into separate class/entity. But this make it problem, because the new class now cannot access the encapsulated fields it could access previously. Various languages give you various tools how to solve this problem. You could make them public, internal or make the class a "friend", or whatever.

The thing is that OOP modeling and design is extremely complex area with lots of unsubstianted "what to do" and "what not do" and every time you present a solution to a problem someone comes with similar problem where the solution doesn't work. It all comes down to experience. There have been written whole books, blogs and seminars about this topic. There is no way to answer your question with simple, few hundred words post.


问:
Client wants source code, but it contains a lot of shared code I reuse with other projects
I have a client who would like me to deliver the source code with a developed application binary. They originally said nothing about source code, but they recently said they need it. The contract is not finalized. They agreed to the work, did not sign, and then came back with this clause.

The issue is: I have a code base I've created over the years and used as a template for most of the applications I write. It is far larger than the scope of the project.

I also intend to use it for a product, so I really don't wish to provide it for a relatively small project.

I'm guessing this is not the first time that this has happened in this industry. What is the best way to circumvent this issue? I'm guessing things like shared libraries could help.

答:
Earlier I usually provided the source code (libraries and all) under a MIT license to the client. If your libraries are well organized you only provide the needed files/resources for that particular client but nothing more. I think that is fair for both me and the client. However there was always the issue of new code written for that particular client under contract that was not part of the library before. So I started to discuss the issue with the client before starting the project. Some clients wanted ownership of that code, some don't (I always gave negative incentives, like higher prices for those who do). But, really for some clients that discussion was very confusing and sometimes I ended up talkin for 3 or 5 different people (including their lawyer) just to get the project approved.

So now all my libraries are part of a custom framework I always use to develop and I explain the client that I will use this framework but that the framework is a different product with a different license. (Sometimes I use "software components" when explaining because "framework" may be unkown to them). I always provide the code of the used files under a MIT license and (because all the code is well organized) the low level code (even the new) remain in the framework (to be reused by me and by them) but the code relating to their application only is for them to keep under their own terms (that code most probably would be useless for me to reuse in another project). Of course all that is properly written in the contract. I think this is fair too.

The key is: "these components are a different product" and all is written in a contract before starting.

So yes, you idea about using shared libraries may be right. However, I ask you, why don't you provide them the source code you used, under a license that will allow them to reduce their risk? I think that would be fair.


问:
Modular Database, Inheritance of Schema
Consider multiple relational database schemas that have an inheritance dependency structure as known from OOP systems:

Tables are just a placeholder for arbitrary database objects such as Views, Stored Procedures, etc.

Are there any methods or tools that might help me express this abstraction? Such as a package manager that builds modular create and upgrade scripts?

(I am not talking of O/R Mapping within one database schema. Actually I am primarily thinking about an BI application, so there is no ORM anyway.)

答:
Perhaps Liquibase can help with its include tag. Put the more common table definitions in separate changesets. Then include these in the more specific ones.

This allows you to maintain the different levels of tables separately, but generate specific databases as required. Plus it adds all the versioning options of Liquibase.

For more information see the documentation of the Liquibase include tag.

Title: Modular Database, Inheritance of Schema


问:
Send heavy computation jobs from web server to another process and wait for response
I know it is a common practice to send cpu-bounded heavy tasks to background processes, in order to free a web server to serve other requests.

But - what if the request must know the result of that computation? Is there a known pattern, where the web server waits for a background process to finish its job, before it responds? I couldn't find any example of this use case.

In my case, for instance, I want to send an HTTP post request's body to Spark Streaming process that runs separately from the server, wait for the result and then respond to the request. (Server and Spark Streaming communicate through Kafka)

Many thanks

答:
What you are describing is asynchronous programming, and more specifically the non-blocking IO model. It has concrete implementations in many languages, including Go, JavaScript( NodeJS ), Clojure, Erlang, C#, P, F#, Python, Perl, Ruby, C, etc.

The Go language, for example, was designed with exactly this sort of problem in mind. It uses goroutines to hand off execution to a non-blocking process. There is an example app floating around somewhere that is a url shortener app that fronts requests with a simple routine and passes off the shortener computation to a goroutine that can then be passed on to other logical or physical nodes, allowing the program to scale as much as needed.

If you know JavaScript, consider looking at NodeJS examples using async and Promises.

Your specific implementation will depend on your technology stack. I don't know the details of the implementation of Spark Streaming and Kafka, but the basic idea is that your program creates an asynchronous request to Spark Streaming, which it tracks using a Promise or equivalent. It continues to process new requests while waiting for the existing request result to be returned. Once the result is returned, it sends its response.


问:
What is an initial skeleton of the website called? A Framework?
I am building a website but I am wondering can I call the initial set of pages a framework?

Say I have a project to build a website for a school. Before I start implementing the requirements I have to build a basic structure which includes initial homepage, navbar etc. just basic set-up pages and structure.

The website will be built upon this framework or skeleton. Is it correct to call this a framework?

答: As with any naming question it's hard to say that anything is incorrect, but it would definitely be misleading and/or confusing to use the term "framework" for this. The term "framework" normally refers to something like ASP.NET which provides necessary features like session management, but doesn't impose any particular page hierarchy. Using "skeleton" seems fine though.</p>


问:
C#/MonoGame - Programming enemies and levels in external script files
I'm writing a little game using C# MonoGame and I have idea of scripting enemies in external script files (not necessarily in C#, maybe in lua?).

So for example I have class Enemy in C#. And I want to load external C# class from file, and the class will inherit from Enemy base class and I will use it as enemy.

Maybe it sound dumb, "why don't I just add .cs files to my project with that class and compile it into one executable?" I don't know, just want to know if it is possible and how to do it.

PS: If it helps I'm using Visual Studio Community 2013.

答:
There are two straightforward ways to accomplish this. The simplest is to move your common code to a library then make your enemy a library that your game loads. Your enemies can be Dlls.

If you want to distribute source, and compile enemies at run time, see https://stackoverflow.com/questions/826398/is-it-possible-to-dynamically-compile-and-execute-c-sharp-code-fragments


答:
What Ixrec said.

I would like to add that I would call it a site map, because that's what a sitemap basically is.

The site map may have a public part, which you might want to include in an actual "site map page" presented to the visitors, and a private part, which might contain things like administration pages etc. the existence of which you probably would not want visitors to know.

Title: What is an initial skeleton of the website called? A Framework?

Body:
I am building a website but I am wondering can I call the initial set of pages a framework?

Say I have a project to build a website for a school. Before I start implementing the requirements I have to build a basic structure which includes initial homepage, navbar etc. just basic set-up pages and structure.

The website will be built upon this framework or skeleton. Is it correct to call this a framework?


问:
What is the difference in memory between a variable assigned to null and one not assigned
What is the difference in memory between a variable assigned to null and one not assigned?

I know that there is a difference in usage, but what is the difference in memory?

答:
There is no difference between the two "in memory."

From the Java Language Specification, 4.12.5. Initial Values of Variables :

Every variable in a program must have a value before its value is
  used:

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):

...

For all reference types (§4.3), the default value is null.

...

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

Reference variables at the class or object level will be assigned a null value.

Reference variables at the method (stack) level will have an unspecified value (using the C++ term). In practice this is often null, but the standard does not specify what is in the reference variable, only that it must be assigned before use. Using a reference variable on the stack in any way other than assignment as its first use will result in a compile error.


答:
What is the difference between a variable assigned to null and others not assigned in memory?

There is no such thing as an unassigned variable in Java. Class data members that don't have an explicit assignment are assigned the default value for the type, null for an object, or something akin to 0 for primitive types.

Local variables live on the stack. (Non-primitive locals such as MyType foo also live on the stack, as references.) The stack allocation is simple. If a block contains declarations for local variables, the space needed by those local variables is reserved on the stack. Whether values are assigned to those local variables on adjusting the stack to accommodate those local variables is irrelevant.

The reason it doesn't matter is whether local variables are or are not assigned a value at the time execution enters the block is twofold. One reason is that the size needed doesn't change. Primitives have a fixed size, and non-primitives are actually references. (The referenced object lives on the heap rather than the stack.) The second reason is that using a local variable that hasn't been assigned a value is a compilation error. This leaves it up to the Java runtime whether to give some value (not necessarily the default) to a declared but unassigned local variable.

Body:
What is the difference in memory between a variable assigned to null and one not assigned?

I know that there is a difference in usage, but what is the difference in memory?


答:
Framework has come to mean something like angular.js or .NET, so it would perhaps be misleading to use that word. (Only because of current trends in programming culture, though; it's perfectly reasonable usage otherwise.)

You could refer to your initial set of files as a scaffolding, or as mock-ups if they only exist to show an initial visual design.


答:
First, there is really no need to worry about the space used by local variables. In one line I can allocate an array of 100,000 integers which will take more space than all the local variables that you are ever going to use.

Second, your code is compiled by a compiler which is likely to be clever. If your variable isn't initialized, it isn't used (because the compiler doesn't allow to use uninitialized variables). But if you initialize it to nil, it still isn't used! The compiler will easily figure out that it isn't used and not actually use space for the variable at all. Even if it is used, the compiler will easily figure out that the value is nil, and use nil instead of the the variable.

But third, this is all micro-optimisations that are not going to help you optimise a program in any way. You are trying to save four or eight bytes. Concentrate on saving megabytes if you want to save anything.

And last, while some people claim variables should always be initialised, that's not true in Java. You should only ever set a variable to a meaningful value. Let's say you want to set a variable to the name of a person, and you forget to do this in one code path. If you blindly initialize the variable to nil, the compiler can't tell you. Without the initialisation, the compiler can and will tell you about your mistake.

Title: What is the difference in memory between a variable assigned to null and one not assigned


问:
What does "Increment" mean in agile software development?
In Software Requirements by Karl Wiegers:

Project  teams that  build products incrementally  by  following  an  agile development process also need to understand the requirements that go into each increment.

What does "increment" and "incrementally" mean here?

答:
Here's discussion on SO.

I like the idea of incrementally building something (adding parts), in an iterative way (building each part in a feedback loop).


问:
Is it safe to link apps to w3.org?
I noted my dev team is using some xhtml links that pull something from w3.org within an application as it runs.  Is this practice standard and/or secure/safe?

They are referencing the following URLs:

```<code>w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
w3.org/1999/xhtml
</code>```

答:
These URLs are references to XML namespaces. These URLs define what XML tags are allowed in the document. Every valid XML document needs to include such namespace URLs. When you are using a standardized XML format, like XHTML1-transitional, you should reference the XML namespaces of the standardization body which defined them, in this case the World Wide Web Consortium.

Most HTML parsers will not download the standard definitions from the provided URLs, because they usually already have them. They will only do so when you provide a non-standard URL, so moving the definitions to your own domain would be a much worse solution.

Title: Is it safe to link apps to w3.org?


答:
First off, yes, http://www.w3.org/ is a completely upstanding site that is the repository of the documentation and specifications for html, xml, xhtml, and the like.

Next, you have a significant misunderstanding about what is actually in the xhtml files.

From the documentation on xhtml (notice the link):

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Virtual Library</title>
  </head>
  <body>
    <p>Moved to <a href="http://example.org/">example.org</a>.</p>
  </body>
</html>
</code>```

The xmlns is a name space.  It is closely related to name spaces in xml (again, notice the link). This is a way of grouping the tags and showing what definition they follow.

This brings us to the dtd.  A dtd is a document type definition. It says "if you want to verify that this document is formed correctly, look at this document."  As xhtml is a standard maintained by the World Wide Web Consortium (w3c), it is hosted on their servers. You could host it on your servers, but seriously, no one ever looks - the important parts are built in to web browsers already.

Nothing is pulled at any time with these statements. You can verify this by setting up a proxy such as fiddler or wireshark and watching all of the traffic when requesting the page - see if anything is pulled from http://www.w3.org/ or not (it isn't).

Title: Is it safe to link apps to w3.org?

Body:
I noted my dev team is using some xhtml links that pull something from w3.org within an application as it runs.  Is this practice standard and/or secure/safe?

They are referencing the following URLs:

```<code>w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
w3.org/1999/xhtml
</code>```

Body:
First off, yes, http://www.w3.org/ is a completely upstanding site that is the repository of the documentation and specifications for html, xml, xhtml, and the like.

Next, you have a significant misunderstanding about what is actually in the xhtml files.

From the documentation on xhtml (notice the link):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Virtual Library</title>
  </head>
  <body>
    <p>Moved to <a href="http://example.org/">example.org</a>.</p>
  </body>
</html>

The xmlns is a name space.  It is closely related to name spaces in xml (again, notice the link). This is a way of grouping the tags and showing what definition they follow.

This brings us to the dtd.  A dtd is a document type definition. It says "if you want to verify that this document is formed correctly, look at this document."  As xhtml is a standard maintained by the World Wide Web Consortium (w3c), it is hosted on their servers. You could host it on your servers, but seriously, no one ever looks - the important parts are built in to web browsers already.

Nothing is pulled at any time with these statements. You can verify this by setting up a proxy such as fiddler or wireshark and watching all of the traffic when requesting the page - see if anything is pulled from http://www.w3.org/ or not (it isn't).


问:
Designing entities that should be mutable through the GUI but protected from programmer error
I have a set of entities, for now represented by very simple classes (further simplified for this example):

```<code>public class Item
{
    public string Name { get; private set; }
    public double MainValue { get; private set; }  //should be exposed for editing in GUI
    public double Value { get; private set; }  //should be exposed for editing in GUI
}

public class Record
{
    public Item Item { get; private set; }
    public double Quantity { get; private set; } //should be exposed for editing in GUI
    public double MainValue { get { return Item.MainValue*Quantity; } }
    public double Value { get { return Item.Value*Quantity; } }
}

public class DayAccount
{
    public DateTime Date { get; private set; }
    public IEnumerable<Record> Records { get; private set; }
    public double MainValueGoal { get; private set; }   //should be exposed for editing in GUI
    public double MainValueTotal { get { return Records.Sum(r => r.MainValue); } }
    public double ValueTotal { get { return Records.Sum(r => r.Value); } }

    public void Add(Record record) {}
    public void Remove(Record record) {}
}
</code>```

There is going to be a repository class for accessing, adding and persisting DayAccount entities, but that's pretty much it. The end user should be able to modify some properties of these entities through the GUI if he needs to edit them, but all other operations on them will be pure data analysis and read-only. The entities will also be persisted, read and updated by an ORM, and will serve as models in the MVVM pattern.

What bothers me is that these entities will be passed around heavily, and I would like to protect them from unintentional modifications of their properties in code.

First of all - is implementing any type of protection worth it? Unintentional modifications will only happen in case of a programmer error/poor usage of the class. Maybe the entities should be left fully mutable, and the code well-documented and deemed safe as long as it is thoroughly covered by tests and passes them?

For educational purposes, suppose the protection from unintended changes is mandatory. How can I enforce it? Making the objects completely immutable and cloning them might pose difficulties when working with the ORM. Providing a simple mutable/immutable switch is misleading in a multithread context. Introducing immutable interfaces that expose a mutable object like in this answer doesn't enforce immutability, it just hides the objects - it is more explicit for a user of this code, but doesn't fully protect from a programmer error.

I'm using C# 5 and .NET Framework 4.5.

UPDATE

Okay, I have realized how little I know about domain driven design and its concepts. Anyway, based on the two answers in this thread I've came up with the following design:

There will be a repository class that hides the ORM and persistence logic. The ORM works with DTOs (all setters public, no validation, default constructor). The users of the repository can't see the DTOs but are able to query immutable domain objects that the repository creates based on these DTOs.

For adding/editing entities, a viewmodel is created and its properties populated with values from the domain object. The viewmodel is fully mutable and has all the validation logic. On save, a new domain object is created with the values from the viewmodel, and then saved or updated through the repository.

For me, this poses two new questions. The immutable domain object represents a valid entity, thus all its values should be validated in the constructor. The viewmodel, on the other hand, can hold incorrect values, which are then validated (for example, in the IDataErrorInfo implementation). How do I avoid duplicating the validation logic between the view model and the domain object?

Second question - to store/update a domain object through the repository, I need to track the Id value from the DTO created by the ORM and set it in the domain object. What bothers me is that this is a strictly persistence detail and has no relevance in the business logic. Is it okay that this persistence detail seeps into the domain?

How reasonable is this design? Am I even thinking in the right direction?

答:
I would recommend mapping your DTOs to a domain object and make that domain object immutable

Just give it private setters and create it through a factory, instead of passing around the DTO all over.

Making it immutable is definitely not a bad idea if you think it should be immutable, documenting still has a risk that a new developer will enter the arena and make some initial mistakes. This is not the end of the world but you want to decrease software entropy as much as possible.

However, I would not recommend making your DTO immutable because you shouldn't have a need for it most of the time. It is a dumb, simple object that carries data, but domain object, on the other hand, can be immutable because it reflects real life requirements of the business.


答:
The entities will also be persisted, read and updated by an ORM, and will serve as models in the MVVM pattern.

Why?

I mean, you basically came out and said that you'd like your entity (as used by the business logic and used by the ORM) to be immutable, but that you'd like your model (as used by the UI) to be mutable (at least for the add/edit screen).

So decouple those two things, like they should've been in the first place.

Title: Designing entities that should be mutable through the GUI but protected from programmer error

Body:
I have a set of entities, for now represented by very simple classes (further simplified for this example):

```<code>public class Item
{
    public string Name { get; private set; }
    public double MainValue { get; private set; }  //should be exposed for editing in GUI
    public double Value { get; private set; }  //should be exposed for editing in GUI
}

public class Record
{
    public Item Item { get; private set; }
    public double Quantity { get; private set; } //should be exposed for editing in GUI
    public double MainValue { get { return Item.MainValue*Quantity; } }
    public double Value { get { return Item.Value*Quantity; } }
}

public class DayAccount
{
    public DateTime Date { get; private set; }
    public IEnumerable<Record> Records { get; private set; }
    public double MainValueGoal { get; private set; }   //should be exposed for editing in GUI
    public double MainValueTotal { get { return Records.Sum(r => r.MainValue); } }
    public double ValueTotal { get { return Records.Sum(r => r.Value); } }

    public void Add(Record record) {}
    public void Remove(Record record) {}
}
</code>```

There is going to be a repository class for accessing, adding and persisting DayAccount entities, but that's pretty much it. The end user should be able to modify some properties of these entities through the GUI if he needs to edit them, but all other operations on them will be pure data analysis and read-only. The entities will also be persisted, read and updated by an ORM, and will serve as models in the MVVM pattern.

What bothers me is that these entities will be passed around heavily, and I would like to protect them from unintentional modifications of their properties in code.

First of all - is implementing any type of protection worth it? Unintentional modifications will only happen in case of a programmer error/poor usage of the class. Maybe the entities should be left fully mutable, and the code well-documented and deemed safe as long as it is thoroughly covered by tests and passes them?

For educational purposes, suppose the protection from unintended changes is mandatory. How can I enforce it? Making the objects completely immutable and cloning them might pose difficulties when working with the ORM. Providing a simple mutable/immutable switch is misleading in a multithread context. Introducing immutable interfaces that expose a mutable object like in this answer doesn't enforce immutability, it just hides the objects - it is more explicit for a user of this code, but doesn't fully protect from a programmer error.

I'm using C# 5 and .NET Framework 4.5.

UPDATE

Okay, I have realized how little I know about domain driven design and its concepts. Anyway, based on the two answers in this thread I've came up with the following design:

There will be a repository class that hides the ORM and persistence logic. The ORM works with DTOs (all setters public, no validation, default constructor). The users of the repository can't see the DTOs but are able to query immutable domain objects that the repository creates based on these DTOs.

For adding/editing entities, a viewmodel is created and its properties populated with values from the domain object. The viewmodel is fully mutable and has all the validation logic. On save, a new domain object is created with the values from the viewmodel, and then saved or updated through the repository.

For me, this poses two new questions. The immutable domain object represents a valid entity, thus all its values should be validated in the constructor. The viewmodel, on the other hand, can hold incorrect values, which are then validated (for example, in the IDataErrorInfo implementation). How do I avoid duplicating the validation logic between the view model and the domain object?

Second question - to store/update a domain object through the repository, I need to track the Id value from the DTO created by the ORM and set it in the domain object. What bothers me is that this is a strictly persistence detail and has no relevance in the business logic. Is it okay that this persistence detail seeps into the domain?

How reasonable is this design? Am I even thinking in the right direction?


答: An "increment" in this context is a small piece of functionality. To build "incrementally" means completing (and potentially releasing) your work in small bits at a time, as opposed to one large release. "Iteration" refers to the (small) cycles of work that you go through to be able to release incrementally. They are related, but not interchangeable, terms.</p>

Title: What does "Increment" mean in agile software development?

Body:
In Software Requirements by Karl Wiegers:

Project  teams that  build products incrementally  by  following  an  agile development process also need to understand the requirements that go into each increment.

What does "increment" and "incrementally" mean here?


问:
How to structure programs that interact with databases?
I've just finished a book on MySQL and I'm in the infantile stages of learning to couple that with Java. I know that the technology I need to learn is called JDBC and that it essentially allows you to execute programmatically created SQL statements. I plan on making a database centered records keeping and management program as a long term project. I'm not quite sure how to fit in a program structure to interact with the database.

Why is the typical way this is done, in terms of high level organization?

How do I go about organizing classes to put together SQL statements and work with them and trade info back and forth with the program and handle results?

What are some do's and more importantly, what are some don'ts?

答:
A typical "MVC for the web" program might look something like this:

RDBMS <--> ORM <--> DAL/SL <--> Controller <--> ViewModel <--> View
```

RDBMS - Your database, usually something like SQL Server, Oracle or Postgresql.

ORM - An Object-Relational Mapper, like Hibernate.  The ORM converts tables to class objects, and vice versa.

DAL/SL - Data Access layer/Service Layer/Repository.  This is a layer of abstraction between your DAL and your User Interface that provides data retrieval services, business logic, and so forth.

ViewModel - The View Model maps data between your domain objects and a user interface.  It can also contain user-interface logic.

View - The User Interface.

That ought to keep you busy for awhile.

Body:
A typical "MVC for the web" program might look something like this:

RDBMS <--> ORM <--> DAL/SL <--> Controller <--> ViewModel <--> View

RDBMS - Your database, usually something like SQL Server, Oracle or Postgresql.

ORM - An Object-Relational Mapper, like Hibernate.  The ORM converts tables to class objects, and vice versa.

DAL/SL - Data Access layer/Service Layer/Repository.  This is a layer of abstraction between your DAL and your User Interface that provides data retrieval services, business logic, and so forth.

ViewModel - The View Model maps data between your domain objects and a user interface.  It can also contain user-interface logic.

View - The User Interface.

That ought to keep you busy for awhile.


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答:
I find it easier to keep track of what I'm doing if I can see the entire function all at once. So here's how I prefer to write functions:

Short enough to fit on my monitor with a reasonable font.

If it needs to be longer than #1, short enough to print on a piece of paper in a reasonable font.

If it needs to be longer than #2, short enough to print 2-up on a piece of paper.

I rarely write functions longer than that. Most of those are giant C/C++ switch statements.

ContentLicense: CC BY-SA 2.5


问:
Why should ViewModel route actions to Controller when using the MVCVM pattern?
When reading examples across the Internet (including the MSDN reference) I have found that code examples are all doing the following type of thing:

```<code>public class FooViewModel : BaseViewModel {
    public FooViewModel(FooController controller) {
        Controller = controller;
    }
    protected FooController Controller { get; private set; }

    public void PerformSuperAction() {
        // This just routes action to controller...
        Controller.SuperAction();
    }

    ...
}
</code>```

and then for the view:

```<code>public class FooView : BaseView {
    ...

    private void OnSuperButtonClicked() {
        ViewModel.PerformSuperAction();
    }
}
</code>```

Why do we not just do the following?

```<code>public class FooView : BaseView {
    ...

    private void OnSuperButtonClicked() {
        ViewModel.Controller.SuperAction();

        // or, even just use a shortcut property:
        Controller.SuperAction();
    }
}
</code>```

答:
Consider the model being just data. It doesn't make choices, and it doesn't know how to render.

A product can be a model.

A list of products can be a model.

A bundle containing the list of products, the cart and the information about the current user is a model.

The last model from the list corresponds to the data you need to render the page, but it shouldn't know how to render itself, because it's not the task of the model.

In order to render it, a view is used, given that the controller may pick different views depending on the context. It will use for example a view to render data to an ordinary guest visitor, a different view for an authenticated user, and a third view if the user is an administrator. Same data, different modes of displaying it.


答:
Consider this a blend of two basic MVCs (this assumes you know the basic MVC).

First, deeper MVC pair is:

M = model

C = controller

V = view model

Second, upper MVC pair is:

M = view model

C = collapsed / minimal / interspersed (OnSuperButtonClicked is part of it)

V = view.

With this separation, of course view from one triad cannot access model, nor the controller, from other triad.

Title: Why should ViewModel route actions to Controller when using the MVCVM pattern?

Body:
When reading examples across the Internet (including the MSDN reference) I have found that code examples are all doing the following type of thing:

```<code>public class FooViewModel : BaseViewModel {
    public FooViewModel(FooController controller) {
        Controller = controller;
    }
    protected FooController Controller { get; private set; }

    public void PerformSuperAction() {
        // This just routes action to controller...
        Controller.SuperAction();
    }

    ...
}
</code>```

and then for the view:

```<code>public class FooView : BaseView {
    ...

    private void OnSuperButtonClicked() {
        ViewModel.PerformSuperAction();
    }
}
</code>```

Why do we not just do the following?

```<code>public class FooView : BaseView {
    ...

    private void OnSuperButtonClicked() {
        ViewModel.Controller.SuperAction();

        // or, even just use a shortcut property:
        Controller.SuperAction();
    }
}
</code>```


问:
Would SQLite be less useful without accepting inserts of non-numeric values into numeric columns?
In SQLite the following statement would be successful and the string would be inserted/updated into the SALARY column which is of type INTEGER:

```<code>update employee set salary='TOO MUCH' where emp_id=1;
</code>```

Note that zero will not be inserted/updated but the actual "TOO MUCH" string, so this is not about authomatic type conversion.

The FAQ states:

This is a feature, not a bug. SQLite uses dynamic typing. It does not
  enforce data type constraints. Data of any type can (usually) be
  inserted into any column. You can put arbitrary length strings into
  integer columns, floating point numbers in boolean columns, or dates
  in character columns. The datatype you assign to a column in the
  CREATE TABLE command does not restrict what data can be put into that
  column. Every column is able to hold an arbitrary length string.
  (There is one exception: Columns of type INTEGER PRIMARY KEY may only
  hold a 64-bit signed integer. An error will result if you try to put
  anything other than an integer into an INTEGER PRIMARY KEY column.)

So this behaviour is clearly intentional, nevertheless I wonder why SQLite has this behaviour, since most other SQL databases I know of behave quite differently, they would rise an error, or convert the string 0, when trying to insert a non-numeric string into a numeric column.

Would the SQLite library be less useful without this behaviour?

Is this made so by design to keep the library small and fast?

Would the SQLite library be significantly slower or bigger in order to rise errors when triying to insert a string into a numeric column?

答:
No, dynamic typing requires both more storage space and more processing time, especially since they also add type affinity, meaning it has a preferred type that the programmer is free to ignore.  It is truly an intentional feature with real trade off costs.  Those costs are effectively negligible for the use cases SQLite targets, but they are still there.

The usefulness of such features is hard to see because you're not accustomed to having it available to you.  The workaround for its lack feels more natural to you now.  Because of your prior experience, you're thinking of it as an INTEGER field which shall never be anything else, but SQLite sees it more as a field of any type, but probably will mostly contain integers.  Perhaps it is a ZIP code for a company that mostly does business in the U.S., but has a handful of Canadian customers.  Allowing the user to specify an integer affinity will save a lot of space over making it a string in every row, but still gives you that option.


问:
Safest way to use and store User's third party credentials
I'm working on an add-in that will integrate git into the VBA IDE. I'm using the LibGit2Sharp library under the hood, which supports User name and password credentials, but not SSH Keys. I would use GitHub's SSH Keys if the library supported them, but it doesn't.

So, I can easily enough ask the user for their credentials prior to trying to interact with the remote repository, but I can feel the "bug" reports coming in already.

Why do I have to provide my password every time I try to push to my repo?

So...

Question 1:

Is it safe and acceptable to keep the password in memory after the user has entered it the first time? If there are caveats to that being safe or unsafe, what are they?

Question 2:

I can also see users not wanting to keep entering their password even on the first time they push during a session. Would it be safe enough to encrypt (not hash) the user name and password and store them along with the add-in's other configuration settings?

I mean, Visual Studio doesn't ask me for my GitHub credentials each time I start up the IDE, so it must be possible to do this relatively safely. But how?

I have read through many related questions, but feel no closer to knowing how to go about safely using my users' credentials in my add-in. Most of the existing questions relate to websites and databases, where the right answer is "don't store the password in a recoverable way, salt and hash it and store the hash only", but in this instance, it's not a password to my service. I need to secure it the best I can, but in a recoverable way. Otherwise, there's no way my program can "log into" their repository on their behalf.

答:
The safest way to "store User's third party credentials" is to not store them - if you store them, you have two major issues:

they may change before you update your cache of them (seen this several times)

your app could be compromised, compromising unknown numbers of users' third-party creds

And probably many more.

You either need to use a different system (OAuth, OpenID, LDAP/AD, SSH keys, etc), or you need to get the user's credentials every time they want to use them.

Saving them is only going to cause you heartache down the road.


问:
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.

答: I was a part of a mainframe support team that did shifts with other support teams in a data center. After the shift we would usually have a briefing with managers and the team of the next shift.  One day our new director showed up and asked the question: "Why average CPU load during your shift was only 72%, while previous shift shows near 95%? I think if we try real hard, we could eventually achieve 100% CPU load!"</p>

OwnerDisplayName: Boris Okner


问:
Deciding factors in pair programming
Are there specific things that you look out for before getting the team into pair programming? Obviously pairing someone who's great with C++ with another who knows ASP.NET best won't get me far, but how about someone who's great with C++ with another who knows Java best but can pick up C++ quick enough? </p>

<p>What else? Experience levels? Character traits? </p>

答:
You shouldn't look at pair programming in what language one knows better than the other, I believe if you want a program to be done in C++ pick 2 people that are good at that, or a fast learner, the same goes to any other language/technology.

Try looking at other assets that the two might have, they should have always different approaches, if they fight over ideas that's a good thing because from 2 good ideas a great one might be found, unless it gets ugly.

Also a pair should always be of people with similar skills otherwise one will be doing all the work and the other trying to catch up, worst case scenario it will take double, or more, of the time as if the best person would be doing it all alone, as he will always be explaining what he does.

This is from my experience at university as we always do works in teams, working with people that have similar skills, to me, has always proved to be more rewarding.

Title: Deciding factors in pair programming


问:
Manager reading version control commits
Our manager is monitoring the Git commits on all of our projects; usually this isn't a problem, and I love the fact that version control provides a log of all work that's happening, especially for later auditing and analysis (in case anything goes wrong).

However, the manager has made a few comments asking what people are working on when he sees a commit that reads "style fixes" or any commit message that does not reference a ticket number in our task management system.

Is there a social or technical solution to this?

Further information: this is a maintenance project, so there's a bunch of "had to do A then B then C and then D and then finally got to implement X" tasks happening.

More information: the particular commit message that raised a flag with the manager was close to "included a better way to X, Y and Z" which is more of a refactoring message rather than a simple stylistic fix.

答:
This bugs me too (no pun intended :).

Most helpful check-ins contain comments that are unique, and specific to not only what changed, but why.  I sometimes end up putting paragraph comments.

I occasionally get into situations where a UI requirement bounces back and forth once development has started, requiring me to essentially bounce the code also (yeah, real world sucks sometimes).  In these cases, I see it as even more important that my comments provide clarity as to why the bounce, and more importantly why the code ends up where it does.  Then, when management comes back after speaking to the customers and wants to know why, I can show them without having to remember the whole experience turn-by-turn.

OwnerDisplayName: anon

Title: Manager reading version control commits


问:
Rethrow the same exception to provide more info
Is it a good practice to rethrow the same exception to provide more specific information? For example:</p>

```<code>var sitemap = "a string containing an XML document";
try {
   // throw InvalidXmlException if the document is not well formed
   parse(sitemap);
} catch (InvalidXmlException e) {
   throw new InvalidXmlException("The sitemap is not well formed: " + e.getMessage());
}
</code>```

答:
Depends

If your method is doing something that will be visible to the end user, security becomes a concern.  You should never throw low-level exceptions back to the user on distributed systems.

Your catch() statement should encapsulate the low-level error and only write it to a (more) secure logging mechanism.  One that is only easily accessible by support personnel, not to the general public.

Then, create and throw a new, generic, exception type that tells the user enough that they can intelligently report it, but doesn't give them the keys to the kingdom.

For all other exceptions, it's generally best to catch the exception at the point where it can actually be handled.

For example:  If you have a business class that calls several data classes, the business class may be best suited to actually handle any data exceptions (meaning give them context in the grand scheme of things).  So, don't catch in the data classes at all.

Your mileage may vary.


答:
Often the stack trace in an exception is of no value and in such cases no harm is done in throwing a new exception.

If you don't know what happened you of course retain all the data you can for debugging purposes.  However, in well-written code there will be few such exceptions, most exceptions will be because the program is a victim of outside forces.  If you know what the outside force is that caused the problem the most informative thing to do is tell the user that.

If you know it failed to find the job you just told it to work on why do you care what it was executing?  The important information is that the job wasn't found.  (I have in mind a case where each job has a directory with some megabytes of data that's not in the database.)

Title: Rethrow the same exception to provide more info

Body:
Is it a good practice to rethrow the same exception to provide more specific information? For example:</p>

```<code>var sitemap = "a string containing an XML document";
try {
   // throw InvalidXmlException if the document is not well formed
   parse(sitemap);
} catch (InvalidXmlException e) {
   throw new InvalidXmlException("The sitemap is not well formed: " + e.getMessage());
}
</code>```


问:
Arrays' subscripts priority
I was reading a lecture on arrays for Fortran 90
and I came across this sentence :
'Fortran always stores by columns - the first subscript
varies more rapidly than the second, and so on.'

What does the author mean to say ?

答:
As an example, if you have an array A such that A(1, 1)=100, A(2, 1)=200, A(1, 2)=300, A(2, 2)=400, and if you have the following line in your Fortran 90 code

```<code>print*, A
</code>```

you will get "100 200 300 400" in your output instead of "100 300 200 400".

Title: Arrays' subscripts priority

Body:
As an example, if you have an array A such that A(1, 1)=100, A(2, 1)=200, A(1, 2)=300, A(2, 2)=400, and if you have the following line in your Fortran 90 code

print*, A

you will get "100 200 300 400" in your output instead of "100 300 200 400".


问:
Fortran 90 - How to create a coordinate system
So I need to code a simple program, and I need to define 2D coordinates?

Is there any coordinate system I can use in Fortran?

I was told it might have to be all in arrays? And if so, can anybody push me in the right direction as to how to set up 2d arrays?

Many thanks.

答:
Although mathematically you need 2D concept to deal with points in a 2D space, you can use 1D arrays in your Fortran code to accomplish your task. For instance, if you have 100 points in a 2D plane to work with, you can define two 1D arrays x and y as follows:

```<code>real:: x(100), y(100)
</code>```

and then you can treat x(i) and y(i) as a pair representing the ith point, and perform whatever calculation you want.

Body:
Although mathematically you need 2D concept to deal with points in a 2D space, you can use 1D arrays in your Fortran code to accomplish your task. For instance, if you have 100 points in a 2D plane to work with, you can define two 1D arrays x and y as follows:

real:: x(100), y(100)

and then you can treat x(i) and y(i) as a pair representing the ith point, and perform whatever calculation you want.


问:
Should I represent physical accessories of a system as classes in software?
I am redesigning a system comprised of a data-acquisition unit and a lot of different sensors (voltage sensor, angle sensor, pressure sensor, etc.).

In the software domain model, there is a base Sensor class, from which every concrete sensor derives.

```<code>public abstract class Sensor
{
    public virtual String Name { get; }
    public virtual UnitOfMeasurement Unit { get; }
    public virtual int SamplingRate { get; }
    public virtual CalibrationModel Calibration { get; }
}
</code>```

Every one of these subclasses represent a physical sensor sold by our company, and has a "hardcoded" value for each property. For example VoltageSensor has "Voltage" as Name, "UnitOfMeasurement.Volt" as Unit, "1000" as SamplingRate, etc.

The current problem I am trying to solve is this:

Each time that a new actual sensor hardware is developed and added to our portfolio, we need to do the following "shotgun surgery":

Create a new Sensor subclass;

Perform some scattered, minor changes on the rest of the system (due to depencencies, etc.);

Release an update to our client base.

As I understand, each physical sensor (the hardware) is a conceptual unit, and as such should be able to be "plugged" to a running system so that it doesn't need to be recompiled and redeployed. Since this is not what's happening, I wonder how could I achieve this "pluggability" and still keeping the polymorphic behavior that is working well so far (except for each time we need to change the portifolio).

Is there some "Configuration over Polymorphism" alternative design that I could take?

答:
When there are a lot of sub-classes of a class which don't differ at all in their behavior (method implementations) and only differ in their values, it is often a good idea to represent them all with one class and read their previously hard-coded values from a configuration file, database table or other data source.

To add a new sensor type, you would then just have to add a line to the configuration. Recompiling becomes unnecessary and when your configuration is in a human-readable format it could even be done by someone without programming knowledge.

When you do it smart, you can even make it possible to re-read the configuration while the program is running, so an update doesn't even require to restart the program.