答:
absolutely never.

Let's assume you have two functions A() and B(). If A() must call B() or it will not work, then sure A() should call B(). If not then A() shouldn't at all care or know about B()'s existence.

Otherwise you are doing two things:

You are unnecessarily [coupling][1] the two functions. what if in future you'll want to alter their order, or call one somewhere else?

You are obfuscating what is happening in your program. if you have a flow that says: *do A then Do B, if B success then do C, then somewhere in your program there should be code to describe this process i.e :

```<code>A();
result = B();
if (result) then
    C();
</code>```

See also: Coupling (computer programming) on Wikipedia

Body:
absolutely never.

Let's assume you have two functions A() and B(). If A() must call B() or it will not work, then sure A() should call B(). If not then A() shouldn't at all care or know about B()'s existence.

Otherwise you are doing two things:

You are unnecessarily [coupling][1] the two functions. what if in future you'll want to alter their order, or call one somewhere else?

You are obfuscating what is happening in your program. if you have a flow that says: *do A then Do B, if B success then do C, then somewhere in your program there should be code to describe this process i.e :

A();
result = B();
if (result) then
    C();

See also: Coupling (computer programming) on Wikipedia


问:
What's wrong with comments that explain complex code?
A lot of people claim that "comments should explain 'why', but not 'how'". Others say that "code should be self-documenting" and comments should be scarce. Robert C. Martin claims that (rephrased to my own words) often "comments are apologies for badly written code".

My question is the following:

What's wrong with explaining a complex algorithm or a long and convoluted piece of code with a descriptive comment?

This way, instead of other developers (including yourself) having to read the entire algorithm line by line to figure out what it does, they can just read the friendly descriptive comment you wrote in plain English.

English is 'designed' to be easily understood by humans. Java, Ruby or Perl, however, have been designed to balance human-readability and computer-readability, thus compromising the human-readability of the text. A human can understand a piece of English much faster that he/she can understand a piece of code with the same meaning (as long as the operation isn't trivial).

So after writing a complex piece of code written in a partly human-readable programming language, why not add a descriptive and concise comment explaining the operation of the code in friendly and understandable English?

Some will say "code shouldn't be hard to understand", "make functions small", "use descriptive names", "don't write spaghetti code".

But we all know that's not enough. These are mere guidelines - important and useful ones - but they do not change the fact that some algorithms are complex. And therefore are hard to understand when reading them line by line.

Is it really that bad to explain a complex algorithm with a few lines of comments about it's general operation? What's wrong with explaining complicated code with a comment?

答: Comments that explain what the code does are a form of duplication. If you change the code and then forget to update the comments this can cause confusion. I am not saying don't use them, just use them judiciously. I subscribe to the Uncle Bob maxim: "Only comment what the code can't say". </p>

ContentLicense: CC BY-SA 3.0


问:
Going TDD in the middle of the project
They want us to develop new features of a product with TDD.
I know that they don't usually write tests for legacy code of already developed modules.

But yet, what if new features have to be added to the legacy modules and we still want to stick with TDD?

答:
The problem you may quickly hit is that in order to test a particular piece of code, you should make testable the code surrounding it. Changing the surrounding code requires testing as well, which, in turn, requires even more changes.

Practical example. A year ago, I had to work on a... let's call it legacy system. Millions of lines of C# code. Maintainability index (MI) reaching sometimes zero (hint for those who never used MI in Visual Studio: going below the MI of 50 is quite difficult: you really have to start writing spaghetti code on purpose). Methods containing up to 4 000 LOC of procedural code. And obviously zero tests, because, frankly, everybody knows writing and maintaining tests costs money.

Since adding the most basic feature was causing hours or days of wasted time (plus time wasted resolving bugs discovered later in production, then days fixing the bugs introduced when resolving the previous bugs), I was thinking about adding at least a bit of testing.

When I left a project, there were indeed a few hundred tests. Those tests were covering the parts of the code which I put in separate classes and which were independent enough from the remaining code base. This is easy enough to do, but also not very useful. Yes, those tests covered some business rules, but their scope was very limited.

I was also thinking about adding more substantial testing, but unsuccessfully.

The major problem was that nearly every piece of code was relying on the database. I tried, on paper, to abstract the database in order to be able to replace parts of it by mocks and stubs. On paper, it worked, but it would require a tremendous amount of time to actually implement.

Another problem, obviously, was the spaghetti aspect of the code. How would you unit test a 4 000 LOC method which needs 16 parameters to be passed to, given that those parameters are not documented (and nobody really knows how some of them should they be used), and trying to replace them by stubs causes weird bugs in weird locations?

So yes, you can introduce tests, including test driven development, on the parts which are being changed, but if the code base is a mess, the scope of those tests will be too small for them to be particularly useful.

What I can personally suggest is to start refactoring modules one by one (hopefully they are interacting through interfaces and are independent enough from each other otherwise), and ensuring those modules have tests. Once you have sufficient code coverage, you'll notice that testing new features is much easier.

Title: Going TDD in the middle of the project


问:
how often do we need to do appraisal for a developer?
I have this question since my friend told me that if we have frequent appraisal such as 4 months or 6 months once, people will be turned to a money minded.

But I am thinking this in another aspect like, people will be getting feedback and boost quickly than one year appraisal. We do not need to increase the salary much. But the token advancement would help them to get some refreshment.

答: After being in management for a few years after being a developer for many years (and headed back TO development), I believe that regular, non-formal appraisal is important.  Not everyone needs this, but human nature dictates that saving this for once or twice per year is detrimental.  Everyone needs regular feedback, not only for motivational purposes, but just to help keep someone from straying too far off the path.  No one likes being kept in the dark on the value they're perceived to add (or improvements they need to make).</p>

ContentLicense: CC BY-SA 2.5


问:
Enforcing manual inclusion of a specific header file (banned.h)
Banned.h is a list of ANSI C functions that Microsoft is trying to persuade programmers to deprecate. I already know how to enforce automatic inclusion of banned.h (such as the answer to Ensuring that headers are explicitly included in CPP file). Unfortunately, that answer has an important drawback.

Forced inclusion in project settings always includes the forced header first. Unfortunately, most of Microsoft's own system header files are not banned.h compliant, and many third party library headers are also not banned.h compliant. Microsoft claims that their usage of the banned APIs are safe, and has no intention of changing this situation. The primary way to use the system headers, then, is to include them before banned.h.

One way to solve this is to make a kind of meta_banned.h, which includes all possible system headers that are used anywhere in your project, as well as all the headers for any non-compliant third-party libraries, prior to including the regular banned.h. This is the first thing I did, but it causes an unfortunate hit to compile time because some of the third-party libraries have extensive headers.

We ended up with a hybrid approach--the meta_banned.h includes some system headers, and then the project settings for certain exceptional CPP files include the third-party headers as part of the force-include settings on that particular file. This works, but it's ugly and painful to maintain. The per-CPP-file forced includes in particular seem ugly.

What I really want is a method to ensure that banned.h is included somewhere in each file, not necessarily at the top. As long as it's included at some point, I consider the file compliant. If it's not included, I want to generate a build error. Any suggestions?

答:
After much debate, we found a method that we like, but it involved other substantial changes to the project. We turned on pre-compiled headers. Within the pre-compiled header, we first include any and all system headers (and other third-party library headers) that are not compliant with banned.h, and then we include banned.h.

This has a lot of properties that we care about:

It doesn't slow down the build, even when rarely used headers are included. Actually, a full build now takes less than half as long as it previously did, because pre-compiled headers are an optimization.

You can't inadvertently leave out banned.h, because the compiler enforces inclusion of the pre-compiled header. Pre-compiled headers are a whole-project setting in Visual Studio, and individual files have to explicitly opt-out if they don't want to use them. So banned.h is cleanly enforced everywhere.

We can either force-include the pre-compiled header to avoid changing every source file, or we can add it to the top of every source file. This provided a nice migration path. All of our exception rules for particular source files went away.

All the compilers we care about (GNU C++, clang, Visual C++) support pre-compiled headers, and the support is similar enough that it doesn't require #ifdefs or similar hacks.

There is one downside that caught us: If you have mixed C++ and C source files in your project, you will need to have separate banned.h files for them. You can't use the same PCH file for both languages. Since all of our C source was from a third party library, we decided to make a separate lib file for it and link it in further downstream, which solved the problem. Now we don't require any customized project settings for individual source files, the project compiles quickly, and we're fully enforcing banned.h.


问:
What are good ways of balancing informative exceptions and clean code?
With our public SDK, we tend to want to give very informative messages about why an exception occurs.  For example:

```<code>if (interfaceInstance == null)
{
     string errMsg = string.Format(
          "Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
          ParameterInfo.Name,
          ParameterInfo.ParameterType,
          typeof(IParameter)
    );

    throw new InvalidOperationException(errMsg);
}
</code>```

However, this tends to clutter up the flow of the code, as it tends to put a lot of focus on error messages rather than what the code is doing.

A colleague started refactoring some of the exception throwing to something like this:

```<code>if (interfaceInstance == null)
    throw EmptyConstructor();

...

private Exception EmptyConstructor()
{
    string errMsg = string.Format(
          "Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
          ParameterInfo.Name,
          ParameterInfo.ParameterType,
          typeof(IParameter)
    );

    return new InvalidOperationException(errMsg);
}
</code>```

Which makes the code logic easier to understand, but adds a lot of extra methods to do error handling.

What are other ways to avoid the "long-exception-messages clutter logic" problem? I'm primarily asking about idiomatic C#/.NET, but how other languages manage it are helpful as well.

[Edit]

It would be nice to have the pros and cons of each approach as well.

答:
For the public SDK scenario, I would strongly consider using Microsoft Code Contracts as these provide informative errors, static checks and you can also generate documentation to add into XML docs and Sandcastle generated help files. It is supported in all paid for versions of Visual Studio.

An additional advantage is that if your customers are using C#, they can leverage your code contract reference assemblies to detect potential problems even before they run their code.

The full documentation for Code Contracts is here.


问:
Why is instance creation the way it is?
I've learned C# over the course of the past six months or so and am now delving into Java. My question is about instance creation (in either language, really) and it's more of: I wonder why they did it that way. Take this example

```<code>Person Bob = new Person();
</code>```

Is there a reason that the object is specified twice? Would there ever be a something_else Bob = new Person()?

It would seem if I were following on from convention it would be more like:

```<code>int XIsAnInt;
Person BobIsAPerson;
</code>```

Or perhaps one of these:

```<code>Person() Bob;
new Person Bob;
new Person() Bob;
Bob = new Person();
</code>```

I suppose I'm curious if there's a better answer than "that's just the way it is done".

答:
Let's take your first line of code and examine it.

```<code>Person Bob = new Person();
</code>```

The first Person is a type specification.  In C#, we can dispense with this by simply saying

```<code>var Bob = new Person();
</code>```

and the compiler will infer the type of  the variable Bob from the constructor call Person().

But you might want to write something like this:

```<code>IPerson Bob = new Person();
</code>```

Where you're not fulfilling the entire API contract of Person, but only the contract specified by the interface IPerson.

Title: Why is instance creation the way it is?

Body:
Let's take your first line of code and examine it.

Person Bob = new Person();

The first Person is a type specification.  In C#, we can dispense with this by simply saying

var Bob = new Person();

and the compiler will infer the type of  the variable Bob from the constructor call Person().

But you might want to write something like this:

IPerson Bob = new Person();

Where you're not fulfilling the entire API contract of Person, but only the contract specified by the interface IPerson.


答:
This syntax is pretty much a legacy from C++, which, by the way, has both:

```<code>Person Bob;
</code>```

and

```<code>Person *bob = new Bob();
</code>```

The first to create an object within the current scope, the second to create a pointer to a dynamic object.

You definitely can have something_else Bob = new Person()

```<code>IEnumerable<int> nums = new List<int>(){1,2,3,4}
</code>```

You are doing two different thing here, stating the type of the local variable nums and you say you want to create a new object of the type 'List' and put it there.

C# kind of agrees with you, because most of the time the type of the variable is identical to what you put in it hence:

```<code>var nums = new List<int>();
</code>```

In some languages you do your best to avoid stating the types of variables as in F#:

```<code>let list123 = [ 1; 2; 3 ]
</code>```

Title: Why is instance creation the way it is?

Body:
I've learned C# over the course of the past six months or so and am now delving into Java. My question is about instance creation (in either language, really) and it's more of: I wonder why they did it that way. Take this example

```<code>Person Bob = new Person();
</code>```

Is there a reason that the object is specified twice? Would there ever be a something_else Bob = new Person()?

It would seem if I were following on from convention it would be more like:

```<code>int XIsAnInt;
Person BobIsAPerson;
</code>```

Or perhaps one of these:

```<code>Person() Bob;
new Person Bob;
new Person() Bob;
Bob = new Person();
</code>```

I suppose I'm curious if there's a better answer than "that's just the way it is done".

Body:
This syntax is pretty much a legacy from C++, which, by the way, has both:

Person Bob;

and

Person *bob = new Bob();

The first to create an object within the current scope, the second to create a pointer to a dynamic object.

You definitely can have something_else Bob = new Person()

IEnumerable<int> nums = new List<int>(){1,2,3,4}

You are doing two different thing here, stating the type of the local variable nums and you say you want to create a new object of the type 'List' and put it there.

C# kind of agrees with you, because most of the time the type of the variable is identical to what you put in it hence:

var nums = new List<int>();

In some languages you do your best to avoid stating the types of variables as in F#:

let list123 = [ 1; 2; 3 ]


答:
The two declarations can be different but are often the same. A common, recommended pattern in Java looks like:

```<code>List<String> list = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
</code>```

These variables list and map are declared using the interfaces List and Map while the code instantiates specific implementations. This way, the rest of the code only depends on the interfaces and it's easy to pick a different implementation classes to instantiate, like TreeMap, since the rest of the code can't depend on any part of the HashMap API that's outside the Map interface.

Another example where the two types differ is in a factory method that picks a specific subclass to instantiate, then returns it as the base type so the caller needn't be aware of the implementation details, eg a "policy" choice.

Type inference can fix the source code redundancy. Eg in Java

```<code>List<String> listOne = Collections.emptyList();
</code>```

will construct the right kind of List thanks to type inference and the declaration

```<code>static <T> List<T> emptyList();
</code>```

In some languages, type inference goes further, eg in C++

```<code>auto p = new Person();
</code>```

Title: Why is instance creation the way it is?

Body:
The two declarations can be different but are often the same. A common, recommended pattern in Java looks like:

List<String> list = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();

These variables list and map are declared using the interfaces List and Map while the code instantiates specific implementations. This way, the rest of the code only depends on the interfaces and it's easy to pick a different implementation classes to instantiate, like TreeMap, since the rest of the code can't depend on any part of the HashMap API that's outside the Map interface.

Another example where the two types differ is in a factory method that picks a specific subclass to instantiate, then returns it as the base type so the caller needn't be aware of the implementation details, eg a "policy" choice.

Type inference can fix the source code redundancy. Eg in Java

List<String> listOne = Collections.emptyList();

will construct the right kind of List thanks to type inference and the declaration

static <T> List<T> emptyList();

In some languages, type inference goes further, eg in C++

auto p = new Person();


答:
It's also about the level of control over what is happening. If the declaration of an object/variable automatically calls a constructor, for example, if

```<code>Person somePerson;
</code>```

was automatically the same as

```<code>Person somePerson = new Person(blah, blah..);
</code>```

then you'd never be able to use (for example) static factory methods to instantiate objects rather than default constructors, that is, there are times when you don't want to call a constructor for a new object instance.

This example is explained in Joshua Bloch's Effective Java (Item 1 ironically enough!)

Title: Why is instance creation the way it is?

Body:
It's also about the level of control over what is happening. If the declaration of an object/variable automatically calls a constructor, for example, if

Person somePerson;

was automatically the same as

Person somePerson = new Person(blah, blah..);

then you'd never be able to use (for example) static factory methods to instantiate objects rather than default constructors, that is, there are times when you don't want to call a constructor for a new object instance.

This example is explained in Joshua Bloch's Effective Java (Item 1 ironically enough!)


问:
How to enforce copyright in source code for use by others
I have coded a project for private use. I currently have no intention for commercializing it  but the plan might change in the future. A friend of mine now wants to use it for his project, and asks if he can incorporate my code into his work.

I have no idea whether he wants to commercialize his project and I do not care if he does. However, I do want to make sure that the copyright of my code still belongs to me regardless what he does with his.

What is the best way to ensure and enforce this? I would rather specify everything clear, sound and upfront than getting into arguments, or worse, legal stuff later.

答:
You need to provide him with a license to use your code.

The Apache license should suffice.  It provide liberal redistribution provisions, while preserving the original copyrights of all contributors, and doesn't contain a "copyleft" provision. Copyleft means roughly that the entity using your code must open-source their code under the same license; commercial, closed-source companies generally avoid copyleft.

When you write code, you own the copyright, period (unless it is a Work for Hire).  Copyright is never transferred to anyone else, unless you explicitly transfer the copyright.  If you are an employee, it is generally assumed that you're creating a Work for Hire; the company owns the copyright.  If you are a contractor, you will generally include a provision that transfers copyright to the entity contracting you.

Enforcement is a bit trickier.  You can't enforce with a license, or any other legal agreement.  All those things do is spell out the terms you expect the licensee to follow.


答: You could, instead of using banned.h, write a Clang analysis program that analyzes your source code. You can use it to enforce whatever coding rules or guidelines you like, not just the banning of a specific set of C functions, and it can also query the source location of any given code and implement location-specific rules.</p>

Title: Enforcing manual inclusion of a specific header file (banned.h)

Body:
Banned.h is a list of ANSI C functions that Microsoft is trying to persuade programmers to deprecate. I already know how to enforce automatic inclusion of banned.h (such as the answer to Ensuring that headers are explicitly included in CPP file). Unfortunately, that answer has an important drawback.

Forced inclusion in project settings always includes the forced header first. Unfortunately, most of Microsoft's own system header files are not banned.h compliant, and many third party library headers are also not banned.h compliant. Microsoft claims that their usage of the banned APIs are safe, and has no intention of changing this situation. The primary way to use the system headers, then, is to include them before banned.h.

One way to solve this is to make a kind of meta_banned.h, which includes all possible system headers that are used anywhere in your project, as well as all the headers for any non-compliant third-party libraries, prior to including the regular banned.h. This is the first thing I did, but it causes an unfortunate hit to compile time because some of the third-party libraries have extensive headers.

We ended up with a hybrid approach--the meta_banned.h includes some system headers, and then the project settings for certain exceptional CPP files include the third-party headers as part of the force-include settings on that particular file. This works, but it's ugly and painful to maintain. The per-CPP-file forced includes in particular seem ugly.

What I really want is a method to ensure that banned.h is included somewhere in each file, not necessarily at the top. As long as it's included at some point, I consider the file compliant. If it's not included, I want to generate a build error. Any suggestions?


问:
Place variables frequently used by the same function on the heap?
Say that I have the following situation:

```<code>void myFunc()
{
    int x;
    //Do something with x
}
</code>```

"x" is placed on the stack which is no doubt fast.

Now, "myFunc" is called very frequently, lets say 10 times per second.
Is it plausible to do something like this:

```<code>int x;
void myFunc()
{
    //Do something with x
}
</code>```

so that x gets allocated in the applications data segment. but it is allocated only once. Since "myFunc" is called so frequently, does the second approach deliver any performance benefits?

答:
It also depends on the architecture. In ARM the first few locals are stored in registers only. As long as you do not call any other functions then these will never go on to the stack.

You need to go the opposite direction. Rather than using globals you should start by limiting the scope if the variables as much as possible. Not only is this good coding practice but it also helps the compiler to better optimize your code.  You should compile with maximum speed optimization then look at the generated assembler code. Even better is to step through this code if your IDE will show you the ASM at the same time as the C code. You will be surprised at what the compiler can do.
See here for a good discussion: https://stackoverflow.com/questions/15180309/local-variable-location-in-memory

Only after you have good readable code that had been optimized by the compiler should you start looking at custom hand coded optimizations. Normally this is only needed for special real-time applications with very strict time constraints.


答:
Would there ever be a something_else Bob = new Person()?

Yes, because of inheritance. If:

```<code>public class StackExchangeMember : Person {}
</code>```

Then:

```<code>Person bob = new StackExchangeMember();
Person sam = new Person();
</code>```

Bob is a person too, and by golly, he doesn't want to be treated differently than anyone else.

Further, we could endow Bob with super powers:

```<code>public interface IModerator { }
public class StackOverFlowModerator : StackExchangeMember, IModerator {}

IModerator bob = new StackOverFlowModerator();
</code>```

And so, by golly, he won't stand for being treated any differently than any other moderator. And he likes to sneak around the forum to keep everyone in line while incognito:

```<code>StackExchangeMember bob = new StackOverFlowModerator();
</code>```

Then when he finds some poor 1st poster, he throws off his cloak of invisibility and pounces.

```<code>((StackOverFlowModerator) bob).Smite(sam);
</code>```

And then he can act all innocent and stuff afterwards:

```<code>((Person) bob).ImNotMeanIWasJustInstantiatedThatWay();
</code>```

Title: Why is instance creation the way it is?

Body:
Would there ever be a something_else Bob = new Person()?

Yes, because of inheritance. If:

public class StackExchangeMember : Person {}

Then:

Person bob = new StackExchangeMember();
Person sam = new Person();

Bob is a person too, and by golly, he doesn't want to be treated differently than anyone else.

Further, we could endow Bob with super powers:

public interface IModerator { }
public class StackOverFlowModerator : StackExchangeMember, IModerator {}

IModerator bob = new StackOverFlowModerator();

And so, by golly, he won't stand for being treated any differently than any other moderator. And he likes to sneak around the forum to keep everyone in line while incognito:

StackExchangeMember bob = new StackOverFlowModerator();

Then when he finds some poor 1st poster, he throws off his cloak of invisibility and pounces.

((StackOverFlowModerator) bob).Smite(sam);

And then he can act all innocent and stuff afterwards:

((Person) bob).ImNotMeanIWasJustInstantiatedThatWay();


答:
The technique I use is to combine, and outsource the validation and throwing altogether to a utility function.

The single most important benefit is that it is reduced down to a one-liner in the business logic.

I bet you can't do better unless you can reduce it further - to eliminate all argument validations and object-state guards from the business logic, keeping only the operational exceptional conditions.

There are, of course, ways to do that - Strongly typed language, "no invalid objects allowed anytime" design, Design by Contract, etc.

Example:

```<code>internal static class ValidationUtil
{
    internal static void ThrowIfRectNullOrInvalid(int imageWidth, int imageHeight, Rect rect)
    {
        if (rect == null)
        {
            throw new ArgumentNullException("rect");
        }
        if (rect.Right > imageWidth || rect.Bottom > imageHeight || MoonPhase.Now == MoonPhase.Invisible)
        {
            throw new ArgumentException(
                message: "This is uselessly informative",
                paramName: "rect");
        }
    }
}

public class Thing
{
    public void DoSomething(Rect rect)
    {
        ValidationUtil.ThrowIfRectNullOrInvalid(_imageWidth, _imageHeight, rect);
        // rest of your code
    }
}
</code>```

Title: What are good ways of balancing informative exceptions and clean code?

Body:
With our public SDK, we tend to want to give very informative messages about why an exception occurs.  For example:

```<code>if (interfaceInstance == null)
{
     string errMsg = string.Format(
          "Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
          ParameterInfo.Name,
          ParameterInfo.ParameterType,
          typeof(IParameter)
    );

    throw new InvalidOperationException(errMsg);
}
</code>```

However, this tends to clutter up the flow of the code, as it tends to put a lot of focus on error messages rather than what the code is doing.

A colleague started refactoring some of the exception throwing to something like this:

```<code>if (interfaceInstance == null)
    throw EmptyConstructor();

...

private Exception EmptyConstructor()
{
    string errMsg = string.Format(
          "Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
          ParameterInfo.Name,
          ParameterInfo.ParameterType,
          typeof(IParameter)
    );

    return new InvalidOperationException(errMsg);
}
</code>```

Which makes the code logic easier to understand, but adds a lot of extra methods to do error handling.

What are other ways to avoid the "long-exception-messages clutter logic" problem? I'm primarily asking about idiomatic C#/.NET, but how other languages manage it are helpful as well.

[Edit]

It would be nice to have the pros and cons of each approach as well.

Body:
The technique I use is to combine, and outsource the validation and throwing altogether to a utility function.

The single most important benefit is that it is reduced down to a one-liner in the business logic.

I bet you can't do better unless you can reduce it further - to eliminate all argument validations and object-state guards from the business logic, keeping only the operational exceptional conditions.

There are, of course, ways to do that - Strongly typed language, "no invalid objects allowed anytime" design, Design by Contract, etc.

Example:

internal static class ValidationUtil
{
    internal static void ThrowIfRectNullOrInvalid(int imageWidth, int imageHeight, Rect rect)
    {
        if (rect == null)
        {
            throw new ArgumentNullException("rect");
        }
        if (rect.Right > imageWidth || rect.Bottom > imageHeight || MoonPhase.Now == MoonPhase.Invisible)
        {
            throw new ArgumentException(
                message: "This is uselessly informative",
                paramName: "rect");
        }
    }
}

public class Thing
{
    public void DoSomething(Rect rect)
    {
        ValidationUtil.ThrowIfRectNullOrInvalid(_imageWidth, _imageHeight, rect);
        // rest of your code
    }
}


答:
In layman's words:

Separating declaration from instantiation helps decouple who uses the objects from who creates them

When you do that, polyporphism is enabled since, as long as the instantiated type is a subtype of the declaration type, all code using the variable will work

In strongly typed languages you must declare a variable stating its type, by doing simply var = new Process() you are not declaring the variable first.

Title: Why is instance creation the way it is?


问:
Functions returning strings, good style?
In my C programs I often need a way to make a string representation of my ADTs. Even if I don't need to print the string to screen in any way, it is neat to have such method for debugging. So this kind of function often comes up.

```<code>char * mytype_to_string( const mytype_t *t );
</code>```

I actually realize that I have (at least) three options here for handling the memory for the string to return.

Alternative 1: Storing the return string in a static char array in the function. I don't need much thinking, except that the string is overwritten at every call. Which may be a problem in some occasions.

Alternative 2: Allocate the string on the heap with malloc inside the function. Really neat since I then won't need to think of the size of a buffer or the overwriting. However, I do have to remember to free() the string when done, and then I also need to assign to a temporary variable such that I can free. and then heap allocation is really much slower than stack allocation, therefore be a bottleneck if this is repeated in a loop.

Alternative 3: Pass in pointer to a buffer, and let the caller allocate that buffer. Like:

```<code>char * mytype_to_string( const mytype_t *mt, char *buf, size_t buflen );
</code>```

This brings more effort to the caller. I also notice that this alternative gives me an other option on the order of the arguments. Which argument should I have first and last? (actually six possibilities)

So, which should I prefer? Any why? Is there some kind of unwritten standard among C developers?

答:
The methods I've seen most are 2 and 3.

The user supplied buffer is actually quite simple to use:

```<code>char[128] buffer;
mytype_to_string(mt, buffer, 128);
</code>```

Though most implementations will return the amount of buffer used.

Option 2 will be slower and is dangerous when using dynamically linked libraries where they may use different runtimes (and different heaps). So you can't free what has been malloced in another library. This then requires a free_string(char*) function to deal with it.

Body:
The methods I've seen most are 2 and 3.

The user supplied buffer is actually quite simple to use:

char[128] buffer;
mytype_to_string(mt, buffer, 128);

Though most implementations will return the amount of buffer used.

Option 2 will be slower and is dangerous when using dynamically linked libraries where they may use different runtimes (and different heaps). So you can't free what has been malloced in another library. This then requires a free_string(char*) function to deal with it.


问:
When, if ever, are basic concurrency optimizations generally made?
Lets say I need to preform the following computationally intensive task

```<code>For i in range(100000000):
    doComplexCalculationWithNoSideEffects(i)
</code>```

Most people I talk to tell me that basically any modern environment (from Java on Windows to Swift on OSX) is going to automatically handle splitting this task up between any parallelizable resources on my machine.  So if I happen to have 16 cores, the work would be automatically split between them.

My question is 1) is this true, and 2) if so, what does this?  The operating system scheduler? The compiler?  I don't like magic in programming, and at my level of understanding, that's exactly what this seems to be.

Oh and if my knowledge is completely remedial, please point me towards where it looks like I should begin learning.  Thanks!

答:
Answer to 1 --its not true!

There are very few(none really) compilers/interpreters clever enough to recognise that a calculation can be split into parallel blocks without affecting the result in some way.

Several languages have support for parallel computation. Most modern C/C++ and FORTRAN support the OpenMP API which allows the programmer control of parallel execution over sections  of a program. R has several plug ins which support parallel computation (mostly using the OpenMP API internally), MATLAB has several extensions to support various type of parallelism  (multicore, GPU explotation, large clusters etc.).

In all cases its up to the programmer to decide whether the computation can safely be done in parallel and the degree/type of parallelism to be used.

If you are using Java or similar then you need to work out how the computation can be broken up and start a number of threads to do the processing. In most cases the single threaded single core calculation will have finished long before you have the multi threaded version debugged :-).


答:
My question is 1) is this true

No, this is complete and utter nonsense.

Automatic parallelization of code that wasn't explicitly written to be parallel has been (one of) the holy grail(s) of optimizers for decades, but it still doesn't work for anything but the most trivial cases. Even just figuring out whether a piece of code has side-effects at all, so that we know whether parallelizing it is even legal, is in the general case equivalent to solving the Halting Problem.

In languages like Haskell, where everything is trivially free of side-effects by definition, the opposite problem exists. There is so much potential parallelism, that we need to restrict it, and again, we haven't figured out how to do this.

Now, automatic parallelization of code that knows it is being automatically parallelized, that is a completely different scenario.

In the Fortress Programming Language, there is a construct that looks like a for loop, but is actually a parallel generator. The language specification says that for loops are executed in parallel, so the Fortress programmers specifically take that into account when writing their for loops.

In the Scala standard library, there are many parallel collections. These are collections which have their foreach, map, flatMap, withFilter, span, etc. methods implemented to use parallelism. Again, if you use a parallel collection, you know that your map is going to be executed in parallel.

Your example would look like this:

```<code>(1 to 100000000).par foreach doComplexCalculationWithNoSideEffects
</code>```

[Note: I made the mistake of actually testing this. The good news is: it works as expected. The bad news is: I should've made the range smaller for testing, it's still running 10 minutes later :-D]

Note the call to the par method on the Range object, which returns a scala.collection.parallel.immutable.ParRange.

In the .NET Task Parallel Library, there is a method called Parallel.For you could use (untested):

```<code>Parallel.For(1, 100000000, doComplexCalculationWithNoSideEffects);
</code>```

In Java, it would look something like this (untested):

```<code>LongStream.range(1, 100000000).parallel().forEach(YourClass::doComplexCalculationWithNoSideEffects);
</code>```

Many other languages also have similar libraries available for parallel computation.

Title: When, if ever, are basic concurrency optimizations generally made?

Body:
Lets say I need to preform the following computationally intensive task

```<code>For i in range(100000000):
    doComplexCalculationWithNoSideEffects(i)
</code>```

Most people I talk to tell me that basically any modern environment (from Java on Windows to Swift on OSX) is going to automatically handle splitting this task up between any parallelizable resources on my machine.  So if I happen to have 16 cores, the work would be automatically split between them.

My question is 1) is this true, and 2) if so, what does this?  The operating system scheduler? The compiler?  I don't like magic in programming, and at my level of understanding, that's exactly what this seems to be.

Oh and if my knowledge is completely remedial, please point me towards where it looks like I should begin learning.  Thanks!

Body:
My question is 1) is this true

No, this is complete and utter nonsense.

Automatic parallelization of code that wasn't explicitly written to be parallel has been (one of) the holy grail(s) of optimizers for decades, but it still doesn't work for anything but the most trivial cases. Even just figuring out whether a piece of code has side-effects at all, so that we know whether parallelizing it is even legal, is in the general case equivalent to solving the Halting Problem.

In languages like Haskell, where everything is trivially free of side-effects by definition, the opposite problem exists. There is so much potential parallelism, that we need to restrict it, and again, we haven't figured out how to do this.

Now, automatic parallelization of code that knows it is being automatically parallelized, that is a completely different scenario.

In the Fortress Programming Language, there is a construct that looks like a for loop, but is actually a parallel generator. The language specification says that for loops are executed in parallel, so the Fortress programmers specifically take that into account when writing their for loops.

In the Scala standard library, there are many parallel collections. These are collections which have their foreach, map, flatMap, withFilter, span, etc. methods implemented to use parallelism. Again, if you use a parallel collection, you know that your map is going to be executed in parallel.

Your example would look like this:

(1 to 100000000).par foreach doComplexCalculationWithNoSideEffects

[Note: I made the mistake of actually testing this. The good news is: it works as expected. The bad news is: I should've made the range smaller for testing, it's still running 10 minutes later :-D]

Note the call to the par method on the Range object, which returns a scala.collection.parallel.immutable.ParRange.

In the .NET Task Parallel Library, there is a method called Parallel.For you could use (untested):

Parallel.For(1, 100000000, doComplexCalculationWithNoSideEffects);

In Java, it would look something like this (untested):

LongStream.range(1, 100000000).parallel().forEach(YourClass::doComplexCalculationWithNoSideEffects);

Many other languages also have similar libraries available for parallel computation.


问:
How do you start a development project with limited knowledge of the domain and programming language?
I am being offered to be a technical lead on a new upcoming project in my company. I have limited knowledge related to this project's domain as well as limited training in the programming language (C#) that this will be written in. I am currently a software developer and leading this project will open many doors for me in terms of experience as a tech lead, learning a new programming language and build my own confidence.

I know for sure that once I give my 100% I will be successful, but this is more philosophical.

Has anyone of you been in such a situation where you have been given an opportunity but not sure if you will succeed? If yes, how did you go about preparing yourself for such a challenge?

How do you start learning about a new domain and programming language (I am a C++ developer right now)?

答:
One year ago, I was working in a Dilbertesque company. On the team working on their main product, they had a technical lead who was... well, not particularly knowledgeable. So one day, the lead decides that code style matters. He spends a few weeks drafting the style guide himself. Then, the team tries to enforce it by hand, but over time forgets more and more about it. From time to time, the team recalls that style should be enforced, makes some efforts, wastes a day for that, and then forgets about it again.

What the lead doesn't know is that:

In C# there is an official set of style rules,

StyleCop enforces them at every commit,

You should enforce style rules at every commit: postponing this until code reviews results in pain and waste of time.

Result: by not having a real technical lead, the team wasted efforts drafting the style rules and originally enforcing them, and continues to waste time enforcing the rules from time to time.

What is a purpose of a team lead?

What is a purpose of a team lead? Why is the team lead I described above a bad one?

To provide the team with technical expertise required by a given project. The ultimate goal is to reduce as much as possible the waste of time which can be occasioned on two levels:

Key decisions. Dead ends and wrong paths. Some key decisions are better be done by a knowledgeable person, because a wrong decision may lead to a situation where the team should get back and pick another decision instead.

Examples of key decisions:

"Should we use WCF or reinvent our own communication layer?"

"Should we implement caching?"

"Should caching be distributed?"

"What's better for our project, WinForms or WPF?"

Technical questions. Developers sometimes don't know very well the language or the framework they are using for a given project. There is always Stack Overflow, but it's often better to have an answer from a person who is right there, available for you, knows you, knows your technical level and your thinking, adapts his answer to you and with whom you can interact, for example when you don't understand some parts of the answer.

Examples of technical questions:

"Why is this piece of code not working?"

"I don't understand lazy initialization."

"Doesn't var means the type is dynamic?"

The technical expertise here is key. You don't become a team lead to learn a language or a framework. You become a team lead because you already has the required knowledge.

Another very important concept is trust. Team leads are not really named by management, but informally chosen by a team. Sometimes, the one who is named and the one who is chosen are the same person, but this is not always the case.

Trust is inherent to expertise, and trust is also a key element in time waste reduction:

Any team tests, often unconsciously, a new technical lead. Team members may be interested by the career of the lead, what books or articles he have written, where have he learnt all the stuff he knows. Team members may also not automatically trust every decision, but either ask him to justify himself, or search for other sources.

For instance, if the lead attempts to enforce a common code style on commit, some members may fight back and ask for a proof that this has any value. A good answer the lead can give is to explain in details the subject and his experience. A bad answer is: "because my previous manager told me that" or "because I read this in a blog".

Another example: if the lead tells that the team should use a message queue service, team members may ask for proof that a MQS will be the best alternative in this particular case. It is then the job of the lead to explain why is this a good choice, and what are the drawbacks of other choices.

A third example: a few years ago, I was a technical lead on a C# project. At the beginning of the project during a code review, I pointed out that a technique which the author was considering being an optimization technique is useless in terms of performance (the compiler does the job as well) and harmful in terms of maintainability. The person wasn't particularly happy with my feedback, so we sat down together for a few hours and I've shown him the IL produced with his code and mine, a few refactoring techniques, Visual Studio's Code metrics, and a few dozen of other things. Few hours later, the guy was happy that in one afternoon, he have learnt more than in the past two years.

With time, the lead becomes a trusted source. Decisions taken by the lead may be accepted as-is by the team. One can think that this is a bad thing (what if the lead actually took a bad decision?), but it's not. If the lead is unsure, he will tell it to his team and expect the point to be discussed. On the other hand, avoiding pointless discussions on points where the lead takes a decision based on his deep knowledge and experience can speed up the project tremendously.

In an ideal project with no time constraints, every decision could be based on evidence. When confronted to a choice, the team will simply follow each alternative and compare the results. In the same way, each answer could be justified and explained in detail.

In practice, there is simply no time for that. I can't possibly test whether my product will perform better with Microsoft SQL Server, Oracle database, IBM DB2, PostgreSQL, MySQL, MongoDB or any other of hundreds of database engines available, and I can't possibly take one to six hours to explain every technical answer I give to my colleagues.

Where does the technical expertise come from?

A crucial mistake the management can do is to name a technical lead who doesn't have the required skills. The team will quickly understand that their lead is not particularly useful, and avoid treating him like one (eventually informally choosing another lead).

In order to win trust of your team, you need technical expertise. You gain this expertise by reading and practicing.

Reading is an essential part of learning experience. By simply practicing, you'll be limited by the knowledge you already have. Reading books, articles, Stack Overflow answers or code gives you an opportunity to have those "Aha! I didn't know that you can do this like that!" and "I never knew this thing is possible in my favorite language!" moments.

Practicing is crucial as well. I'm glad to hire a programmer with no prior professional experience, but certainly not as a technical lead. Again, the main concern is how much can he reduce the waste of time for the team. The lack of professional experience can be particularly harmful for key decisions.

For example:

If you are about to decide whether your team should use Code contracts or not, I don't care that you've read all MSDN documentation about Code contracts: you should be able to tell what are the pros and cons of them based on your experience.

If you've read an article written by a Microsoft's employee, you'll think Code contracts are magic (and believe me, they actually are). If you've read an article written by a guy who tried Code contracts but was more concerned about his CPU usage than the benefits for his project, you would think that Code contracts are difficult to use and to get right (they are, too).

On the other hand, if you've actually used Code contracts on small and large projects, you know the benefits and you know the caveats, you can explain them if needed to your team, but more importantly, you can take the right decision for your team without having to explain them why are you taking this decision.

If you are building an app which relies on WCF, there are no books you can read that will tell you that WCF <s>may be</s> is often painful to configure right. As a technical lead, you're expected to encounter many of the possible WCF-related trouble cases, and know how to solve them.

How do you start learning about a new domain and programming language?

C# in Depth by Jon Skeet can be a good start. And then, practice, practice, practice.

So what should you do?

Giving advice is difficult. I don't know you. I don't know your company. Nor your future role within your future team. Nor your skills.

Still, there is one important thing. Be extremely clear with your manager/boss. If you think, especially after reading my answer, that you don't have the required knowledge and training right now, ask for more training or for more time to handle your own training yourself before starting the project.

Being clear with your manager/boss is crucial. Your manager/boss may not have technical skills, and he may not even know the difference between C++ and C# or between Java and JavaScript. He looks at your CV, sees "C-something: lots of years of experience", and decides to make you the technical lead. If the project end up being a technical failure, you will be the one to be blamed.


问:
Is unifiing ADTs with typeclasses possible?
When i was thinking about language design i got an idea that ADTs (Aglebraic Data Types) and typeclasses could be the same thing. They can both represent a group of types, but in haskell they are not the same thing. Typeclass can be extended later, but ADT can't.

But, sometimes typeclass also cant do everything a ADT can. For example:

```<code>class Shape a where
  draw :: a -> IO ()

data Rectangle = Rectangle Float Float
instance Shape Rectangle where
  draw rectangle = ...

-- no way to put constraint for shape
data Group a = Group [a]
instance Shape Group wheres
  draw group = ...
</code>```

With ADT it's simple and working, but no  new shape can be added:

```<code>data Shape
  = Rectangle Float Float
  | Group [Shape]

draw (Rectangle x y) = ...
draw (Group [ss]) = ...
</code>```

If classes were more like ADTs, language could behave something like this when it comes to booleans (this is not syntax of a real program):

```<code>-- a group of types
class Bool
-- one type with one constructor
data True
-- adding type to group
instance Bool True

data False
instance Bool False
</code>```

This could also be made with numbers, which would look even more rediculous, but i hope u can get my point.

Is it posible that in other language this two things are one? Does any other language work that way? What are the reasons that ADTs and typeclasses should be seperated?

答:
Type classes and Algebraic Data Types are not at all the same thing.  They are not quite opposites but have very different purposes

Type class: defines a set of functions (usually only the signature, with no concrete implementation, although a default implementation can be provided).  At any point in code (not just in the relevant module) an instance may be defined to provide a concrete implementation for a specific type, to add it to the type class.  Creating this instance can be a temporary convenience and not express anything about the nature and purpose of the class. Adding a type to a type class says nothing about its relationship to other types. Ad hoc Polymorphism is the aim.

ADT:  A very specific composite type created from a set of simpler constructs which together define the different states or structures of the ADT.  An ADT may come with no functions beyond the constructors - you could provide a very simple List module that only consisted of data List a = Nil | Cons a (List a) and tell people "Use pattern matching to get the data out, write your own head and tail functions".  Those functions provided with an ADT will be concrete and hard coded to deal specifically with the fixed set of member types.  The relationship between the member types is what the ADT defines (authoritatively and finally).  The main point is to define the different states of the type expressively in a way that makes it easier to write functions for it while minimising the risk of accidentally creating partial functions and enabling the compiler to optimise wherever pattern matching is exhaustive.

They can both represent a group of types

In the Haskell implementation, an ADT typically consists of just one type - the ADT itself.  The set of data constructors which the ADT comprises are values, not types.  Bool is a type but nothing can be of type True or False.  If you create a Tree type with constructors Empty and Node, nothing can be of type Node or Empty, only of type Tree which can have either an Empty or a Node value.  This is a key feature, allowing implementation detail to be encapsulated (if desired) and preventing extension to the set of values (which could break the structure of the type and the functions which work with it).  This is pretty much the opposite of the Type Class, where (of course) every member is a type and the set of types which are members of the class is infinitely extensible.

Almost the only thing they have in common is that they are part of the same type system.  Neither feature would benefit from acquiring the features of the other.  ADTs would be weakened to the point of uselessness (and absurdity) by becoming lose and ad hoc.  Type classes would serve no use if they had to be concrete and fixed.  That is my answer to your final question.

You suggest no benefit from unifying them.  What did you have in mind?

Algebraic Data Types are very common in functional languages.  Type classes were invented in Haskell and are much less common - the development communities of the older functional languages have shown no enthusiasm for adopting them.  Of the few newer languages which have, I know of none that has tried what you suggest (not even Scala).


问:
Is it not direct usage of primitive pointer types form of Primitive Obsession?
Using primitive data types to represent domain ideas is code smell called Primitive Obsession. For example using string data type to represent human name - it is recomended to avoid this by defining domain specific value object with apropriate methods.

But what about pointers?

Is it not primitive obsession to use CItem* or shared_ptr instead of more domain specific types like CItemHandle, CItemLink etc. ?

Edit:

My viewpoint with this question is that usefulness of type is not only about what behaviors it allows, but also about what behavior it don't allows. Primitive type gives you some set of constraints. User defined types can give you different set of constraints.
Thanks to this, user defined type can clearly model domain by using domain constraint and domaing wording in its interface and this also helps with promoting right thinking and in result right decision when making changes in system. User defined type which encapsulates pointer simply gives you more precisse control than pointer itself to enforce proper use of it.

答:
Object pointers are not primitives in the sense that strings or ints are.  A PersonName* is not a Genus* and its not a ProductDecription*.  Unsurprisingly, the equivalent to primitives for pointers is
 pointers to primitives.

Adding an extra level of indirection won't change that either way.


问:
Is Rails 3 ready for use in production?
I'm looking to get a snapshot of Rails 3 at this point in time. We're about to start a new long term project, and I'm wondering if R3 is ready for real use. Or, if there are still a lot of bumps to be worked out. E.g. I saw questions about its compatibility with Passenger. (?)

Thanks!

答:
What is your current rails experience?

If you have prior rails experience and you want to get something out quickly, I'd go with what you know, so Rails 2, and only port afterwards.

If just starting out and no previous experience, I'd go for Rails 3. You would be better off learning the new thing immediately. There's a great rails tutorial out there.

I'm quite confident that Rails 3 is in good shape, though there's bound to be some kinks left and there is new stuff to learn which might slow you down a bit at first.

Title: Is Rails 3 ready for use in production?


问:
How does a DMA controller work?
From Section 5.1.4 Direct Memory Access in Modern Operating Systems by Andrew S. Tanenbaum, Herbert Bos, 2014,

To simplify the explanation, we assume that the CPU accesses all devices and memory via a single system bus that connects the CPU, the memory, and the I/O devices, as shown in Fig. 5-4.

To  explain how DMA works, let us first look at how disk reads occur
  when DMA is not used.

First the disk controller reads the block (one or more sectors) from the drive serially, bit by bit, until the entire block is in
  the
  controller’s internal buffer.

Next, it computes the checksum to verify that no read errors have occurred. Then the controller causes an interrupt. When the
  operating
  system starts running, it can read the disk block from the
  controller’s buffer a byte or a word at a time by executing a loop,
  with each iteration reading one byte or word from a controller
  device register and storing it in main memory.

Q: in the second step,

isn't the data transferred "from the controller's buffer" to the main memory? Why does it say both "from the controller’s
buffer" and "from a controller device register"?

in the second step, can the controller transfer data from its buffer to the main memory, without interrupting to the cpu, and
without involving OS again?

When  DMA  is  used,  the  procedure  is  different.

First  the  CPU  programs  the DMA controller by setting its registers so it knows what to transfer where (step 1 in Fig. 5-4).

  It also issues a command to the disk controller telling it to read
  data from the disk into its internal buffer and verify the checksum.

When valid data are in the disk controller’s buffer, DMA can begin. The DMA controller initiates the transfer by issuing a read
  request over the bus to the disk controller (step 2). This read
  request
  looks like any other read request, and the disk controller does not
  know (or care) whether it came from the CPU or from a DMA controller.
  Typically, the memory address to write to is on the bus’ address
  lines, so when the disk controller fetches the next word from its
  internal buffer, it knows where to write it. The write to memory is
  another standard bus cycle (step 3).

When the write is complete, the disk controller sends an acknowledgement signal to the DMA controller, also over the bus
  (step
  4). The DMA controller then increments the memory address to use and
  decrements the byte count. If  the  byte  count  is  still  greater
  than  0,  steps  2  through  4  are  repeated  until  the count
  reaches  0.

At  that  time,  the  DMA  controller  interrupts  the  CPU  to  let  it know that the transfer is now complete. When the operating
  system
  starts up, it does not have to copy the disk block to memory; it is
  already there.

Q: in the second step, the DMA controller requests the disk
controller to transfer data from the disk controller's buffer to the
main memory. In the first step, the CPU issues a command to the disk controller telling it to read data from the disk into its internal buffer. At the same time, can the CPU also tell the disk controller to transfer data
from the disk controller's buffer to the main memory, when the disk controller finishes transfer data from the disk to the disk controller's buffer, so that there is no need for the DMA controller to tell the disk controller to transfer data from the disk controller's buffer to the main memory? (I can't understand why we need a DMA controller for data transfer between the disk and the main memory, so guess that I miss something important to understand the quote).

A device controller of a device controls the device and performs
operations on the device. What device does a DMA controller control
and perform operations on?

Thanks!

答:
This is not an answer; it is a request for clarification that's too long to fit in the comments.

Before anyone can answer this question, one has to explain clearly the computer system architecture that is being discussed. Namely:

What are the bus systems involved in this description?

Most computer systems have a memory bus.

Most computers have other kinds of bus systems as well.

Does the disk IO go through the memory bus also?

In other words, does the disk uses the address bus lines for addresses, and the data bus lines for data?

Does the disk controller sees the memory bus as ...

A memory bus? That is, it thinks it is talking to a memory chip; i.e. RAS (row access strobe), CAS (column access strobe), ...

Very unlikely - talking to a memory chip requires one to be ultra-precise about issuing commands according to DRAM timing (latencies) - a few clock cycles too early or too late, data loss will occur.

So ... what does the disk controller thinks the bus "actually is" ?

In most computer systems, there is a kind of IO called "Port I/O".

Port I/O may either piggyback on to the memory bus, or they may have another dedicated bus.

The distinctive feature of Port I/O is that one can finish things in a single (or a predefined constant number of) bus cycle - no need to worry about the dangers of DRAM timings.

In more advanced (well, since two decades ago) systems, there are newer types of bus systems. For example, ISA, PCI, AGP, PCMCIA ... SCSI, ATA, SAS, SATA, FC-AL ...

Now, with so many uncertainties being raised about "the computer system that is being discussed", you can understand why you won't get a clear answer for your question.

Yes, I know that it comes from a textbook. You have a copy. I don't. (Not at home - there's one in the office, though.) Therefore, if you need an answer, you will need to show some diagrams and explain what your computer's bus system looks like.

At the very bottom line, though:

A DMA is a programmable device. That is, the CPU has the ultimate responsibility of telling the DMA what to do. Of course, during the time slot where the DMA takes over the system, the CPU will cooperate by letting the DMA run the show.

Under the control of the CPU (and the OS that runs it), a DMA has the ability to take over control for one or more bus (plural) in order to facilitate the transfer of data from the disk controller to the main memory.

During the timeframe where the DMA takes over the bus (plural), the DMA will issue commands over that bus - i.e. in place of its usual controller, i.e. the DMA pretends it is doing the CPU's work.

If the data transfer involves two different bus, the DMA may have to do this to different bus.

To be able to move a number of bytes (words, etc), the DMA contains a loop counter for keeping track of the remaining amount of data to be copied.

To be able to write to the main memory, the DMA contains a memory address register, which is programmable by the CPU, so that the CPU can tell the DMA where to write the data to.

Depending on the system's bus design, the DMA may or may not have to deal with the gruesome detail of DRAM timing cycles.

Once upon a time, some time after DMA has been invented, some peripheral devices start to pre-package DMA onto their controllers - this is called Bus Mastering. Still, whether the DMA sits on the CPU package, the motherboard, or the I/O card, it must be ultimately under the control (programming) of the CPU, because they must somehow negotiate access to the system bus (plural), and the main memory.

Modern computer systems have a dedicated subsystem called the DRAM Controller. If there is one, it is almost certainty that this DRAM Controller will also fulfill the functionality of DMA, that is, it looks like it's a programmable "byte copying loop", and all of the aforementioned complexity is hidden inside the silicon of the DRAM Controller.

If you find it very confusing - I find it confusing too - you will need diagrams. Lots of diagrams. System diagrams. Bus diagrams. Timing diagrams. State transition diagrams. etc.

Title: How does a DMA controller work?


问:
Is it good to split big repository into smaller ones to have separate history/issue etc or keep it big?
We are currently porting our huge svn repo to git and we are thinking to export subdirectories of repository, each one containing source code of independent binaries, documentation or robot tests, into separate git projects.

One of those is a library that is currently being developed and all of the binaries depend on it.

All of those directories/binaries/docs etc are currently developed.

Should we separate all of those into separate git repos or add submodules or keep it as it is one huge repo?

Catalog structure:

```<code>/trunk/src/
    binary1/
    binary2/
    binary3/
    binary4/
    binary5/
    library/
    TA_tests/
    docs/
    scripts/
</code>```

答:
For my work we use separate repos and maintain versions for each module.

Pros

Not all of the modules are required for each project so we are able to easily keep the size of each project down

Commit history is specific to the module

It is easy to use specific versions or branches of the module when needed.

Cons

We have to use a package manager to maintain dependencies

Dependencies can have conflicts e.g. one module requres v0.1.3 of a module called utilities and another module requires v2.0.2 of utilities

Other Thoughts

If the project you are on is a single project with lots of parts it is less important to keep things separate. It might still be easier if each module were separate. But if you have lots of small or medium projects that use various modules then it is very useful to have separate repos.


问:
How to safely chain several API requests for a single user
I am writing a web application with Python and Flask. At a high-level, the web service takes an ID, downloads a file from a third-party API based on that ID, reads and analyzes the data inside the file, and finally returns that analysis to the client.

Since this process takes a fair bit of time, I'd like to have notifications to the client when (1) the file is being downloaded, (2) the file is being analyzed, and (3) the analyzed value has been returned. Since HTTP is based on a single request-response cycle architecture, I have decided to break each step into an API endpoint. The client-side JavaScript will handle chaining the AJAX requests and updating the client of the progress.

Here is the request-response workflow I have in mind:

1a. The front-end makes a request with an ID to a "download" endpoint and then notifies the client that the file is being downloaded.

1b. The server downloads the file and responds to the front-end with the downloaded filename. When this is successful...

2a. The front-end makes a request with the filename from step 1 and some additional configuration values--set when the user initially clicks "submit"--to an "analyze" endpoint and then notifies the client that the file is being analyzed.

2b. The server analyzes the file based on the client's configuration and generates an output file with the analysis. The server then responds with the output filename.

3a. The front-end then makes a request to the "output" endpoint with the output filename from step 2 and notifies the client that the output file is being downloaded locally.

3b. The server simply returns the static file on request. The server then deletes the output file.

Broadly, my question is: does this architecture work? More specifically:

Is there a better way to show progress to the client? This seems like a lot of overhead for that functionality--on the other hand, it's nice to have cleaner API endpoints.

What happens when client A and client B request the same data back-to-back? Client B's server-side process might respond that the output file is ready right before client A's process delete the file. Is there a way to avoid this scenario?

I realize this is a bit messy, but I am pretty new to back-end development and am very open to any suggestions.

Thanks in advance.

答:
There are several parts to your question I will attempt to answer them.

Architecture

As far as architecture goes I would suggest either a simple endpoint that returns the current status of a process or a web socket (if you only support modern browsers). Using a status endpoint the client can simply poll or listen to the socket for status updates. When the status changes to something the client is updated and responds accordingly.

This way you will only have endpoints for each task and a status endpoint. The server then can perform any task in any order or respond with an error if a request is made in the wrong order.

Client Tracking

Two things might help you with solving the client A vs client B.

It sounds to me like you need to track session variables. Keep each clients requests sand boxed from each other by salting the file names with a client specific id or session. This will also help in keeping your site secure. You don't want to allow arbitrary user content to be uploaded and shared with other clients unless you can sanitize it. For example if Client A were malicious and uploaded javascript and Client B were to download it to his browser the javascript will run in the context of your domain and could end up doing nasty things.

Also, it might help to not delete the file right away but to have a separate script clean up at set time intervals. See Cron or Task Schedular.

I have used cron scripts that check a given file location for files older than a given time frame. That way I delete files well after they were needed.


问:
Accuracy proportional to size
I have lists of data I'm trying to organize where the list with the least variation/most precision/closest to the average and most amount of data is most highly rated.
Some of the lists are like 2000 numbers long and others only have 1 number. Obviously the arithmetic mean of a list with one number will be exactly the value of the one number. Any individual value from a list of 2000 numbers might not be as close to the arithmetic mean. When sorting these, all the smaller lists will be higher rated.

It seems really easy, but I can't come up with a way to order the list more proportionally.

Examples of lists:

List 1

12, 20, 15, 17, 9, 19

Average of list:

12+20+15+17+9+19/6=15

Score: (15-12) + (20-15) + (15-15) + (17-15) + (15-9) + (19-15)= 20

List 2

30

Average of list: 30/1=30

Score: (30-30) = 0

List 3

10, 10, 10, 10, 10, 10, 10, 10, 10, 9

Score: (10-10)...etc = 1

Ranking

List 2: Score=0

List 3: Score=1

List 1: Score=20

This is what i have right now. The problem with this is that list 2 will be at the top because its small. I'd like list 3 to be at the top because the score is small and it has a lot of members. I'm not sure how to add weight to size though. List 1 is an example of a list with a lot of members, none of which are really close to the average. Thats two bad things so it should be at the bottom.

As for outliers, they arent treated any differently. If one super high number gives a list a really bad score thats okay.

答:
A common approach to measuring what you're describing is to use the standard deviation of the set of numbers.  Others prefer to use the variance instead.  Fortunately, calculating both is fairly simple once you understand the algorithm.

For the variance and standard deviation, follow these steps:

Find the average of your set of numbers:

float avgValue;
float totalValue = 0;
for( var i in setOfNumbers ){
    totalValue += i;
}
avgValue = totalValue / setOfNumbers.Count();  // or use Length() instead ...
```

<ol start="2">
<li>Sum the squares of the difference from the average value.</li>
<li>Find the variance by find the average from step 2.</li>
</ol>

<pre class="lang-cs prettyprint-override"><code>//Find sum of squares of the difference from average
float sumOfSquares = 0;
for( var i in setOfNumbers ){
    float diffFromAvg = i - avgValue;
    sumOfSquares += diffFromAvg^2; // use your language's square function
}

//find variance
float variance = 0;
variance = sumOfSquares / setOfNumbers.Count();  // or use Length() instead ...
</code>```

If you want the standard deviation, that's the square root of the variance.

This link and this link also offer up some additional explanation for calculating either the variance or the standard deviation.

You said that the longest list you have is 2000 numbers, so you're not likely to need alternative algorithms.  That said there are a number of ways to calculate variance and standard deviation in one pass.

But as with all things in life, there are disputes over the best approach, so do your additional research if you get beyond the basic algorithms.

Title: Accuracy proportional to size

Body:
A common approach to measuring what you're describing is to use the standard deviation of the set of numbers.  Others prefer to use the variance instead.  Fortunately, calculating both is fairly simple once you understand the algorithm.

For the variance and standard deviation, follow these steps:

Find the average of your set of numbers:

float avgValue;
float totalValue = 0;
for( var i in setOfNumbers ){
    totalValue += i;
}
avgValue = totalValue / setOfNumbers.Count();  // or use Length() instead ...

Sum the squares of the difference from the average value.

Find the variance by find the average from step 2.

//Find sum of squares of the difference from average
float sumOfSquares = 0;
for( var i in setOfNumbers ){
    float diffFromAvg = i - avgValue;
    sumOfSquares += diffFromAvg^2; // use your language's square function
}

//find variance
float variance = 0;
variance = sumOfSquares / setOfNumbers.Count();  // or use Length() instead ...

If you want the standard deviation, that's the square root of the variance.

This link and this link also offer up some additional explanation for calculating either the variance or the standard deviation.

You said that the longest list you have is 2000 numbers, so you're not likely to need alternative algorithms.  That said there are a number of ways to calculate variance and standard deviation in one pass.

But as with all things in life, there are disputes over the best approach, so do your additional research if you get beyond the basic algorithms.


问:
How to earn team members respect as team lead
If you were hired into a new company as a team lead (say a team of 10) one of the important things to do is to earn the respect of the members of the team. In the early days the new team lead may know nothing of the team culture, code base and business domain: in other words, is a complete neophyte. </p>

<p>How does one go about this? What are the do's and don'ts? </p>

答:
Some great answers here.  If I were to summarize in a sentence:

Remove barriers, allow them to focus, speak their language, show trust in them (even if it leads to mistakes), and empathize.

Everything else is just a means to an end.


答:
Q1

In the first step, we're NOT using DMA, so the content of the disk controller is read piece by piece by the processor. The processor will of course (assuming the data is actually going to be used for something, and not just being thrown away) store it in the memory of the system.

The buffer in this case is a piece of memory on the hard-disk (controller) itself, and the controller device register a control register of the hard-disk (controller) itself.

Not involving the OS (or some other software) would require some kind of DMA operation, and the section of text you are discussing in this part of your question is NOT using DMA. So, no, it won't happen like that in this case.

Q2

So, the whole point of a DMA controller is to "perform the tedious task of storing stuff from the device's internal buffer into main memory". The CPU will work with both the DMA controller and the disk device. If the disk could do this itself, there would be no need for a DMA controller.

And indeed, in modern systems, the DMA capability is typically built into the hard-disk controller itself, in the sense that the controller has "bus mastering" capabilities, which means that the controller itself IS the DMA controller for the device. However, to look at them as two separate devices makes the whole concept of DMA a little less difficult to understand.

Q3 (kind of)

If you think of the hard disk as the stack of bricks just delivered to a building site, and the processor is the bricklayer that lays the bricks to build the house. The DMA controller is the labourer that carries the bricks from the stack of bricks to where they are needed for the bricklayer, meaning that the bricklayer can concentrate on doing the actual work of laying bricks (which is skilled work, if you have ever tried it yourself), and the simple work of "fetch and carry" can be done by a less skilled worker.

Anecdotal evidence:
When I first learned about DMA transfer from disk to memory was about 1997 or so when IDE controllers begun using DMA, and you needed to get a "motherboard IDE controller" driver to allow the IDE to do DMA, and at that time, reading from the hard-disk would take about 6-10% of the CPU time, where DMA in the same setup would use about 1% of the CPU time. Before that time, only fancy systems with SCSI disk controllers would use DMA.

Title: How does a DMA controller work?

Body:
From Section 5.1.4 Direct Memory Access in Modern Operating Systems by Andrew S. Tanenbaum, Herbert Bos, 2014,

To simplify the explanation, we assume that the CPU accesses all devices and memory via a single system bus that connects the CPU, the memory, and the I/O devices, as shown in Fig. 5-4.

To  explain how DMA works, let us first look at how disk reads occur
  when DMA is not used.

First the disk controller reads the block (one or more sectors) from the drive serially, bit by bit, until the entire block is in
  the
  controller’s internal buffer.

Next, it computes the checksum to verify that no read errors have occurred. Then the controller causes an interrupt. When the
  operating
  system starts running, it can read the disk block from the
  controller’s buffer a byte or a word at a time by executing a loop,
  with each iteration reading one byte or word from a controller
  device register and storing it in main memory.

Q: in the second step,

isn't the data transferred "from the controller's buffer" to the main memory? Why does it say both "from the controller’s
buffer" and "from a controller device register"?

in the second step, can the controller transfer data from its buffer to the main memory, without interrupting to the cpu, and
without involving OS again?

When  DMA  is  used,  the  procedure  is  different.

First  the  CPU  programs  the DMA controller by setting its registers so it knows what to transfer where (step 1 in Fig. 5-4).

  It also issues a command to the disk controller telling it to read
  data from the disk into its internal buffer and verify the checksum.

When valid data are in the disk controller’s buffer, DMA can begin. The DMA controller initiates the transfer by issuing a read
  request over the bus to the disk controller (step 2). This read
  request
  looks like any other read request, and the disk controller does not
  know (or care) whether it came from the CPU or from a DMA controller.
  Typically, the memory address to write to is on the bus’ address
  lines, so when the disk controller fetches the next word from its
  internal buffer, it knows where to write it. The write to memory is
  another standard bus cycle (step 3).

When the write is complete, the disk controller sends an acknowledgement signal to the DMA controller, also over the bus
  (step
  4). The DMA controller then increments the memory address to use and
  decrements the byte count. If  the  byte  count  is  still  greater
  than  0,  steps  2  through  4  are  repeated  until  the count
  reaches  0.

At  that  time,  the  DMA  controller  interrupts  the  CPU  to  let  it know that the transfer is now complete. When the operating
  system
  starts up, it does not have to copy the disk block to memory; it is
  already there.

Q: in the second step, the DMA controller requests the disk
controller to transfer data from the disk controller's buffer to the
main memory. In the first step, the CPU issues a command to the disk controller telling it to read data from the disk into its internal buffer. At the same time, can the CPU also tell the disk controller to transfer data
from the disk controller's buffer to the main memory, when the disk controller finishes transfer data from the disk to the disk controller's buffer, so that there is no need for the DMA controller to tell the disk controller to transfer data from the disk controller's buffer to the main memory? (I can't understand why we need a DMA controller for data transfer between the disk and the main memory, so guess that I miss something important to understand the quote).

A device controller of a device controls the device and performs
operations on the device. What device does a DMA controller control
and perform operations on?

Thanks!


问:
Language support for (syntactic) delegation in Java
Composition over inheritance is an old trend or even accepted state of the art in object oriented programming. It would be even easier to use in Java, if there were language support for delegation. Our IDEs, like eclipse, allow for easy generation of delegating methods, but the result is terrible code clutter. I would rather like to see something like

```<code>class ExtendedList<T> implements List<T> {
  List<T> values = new ArrayList<T>();
  delegate values.*;
  ...
}
</code>```

where delegate is a new language keyword that is nothing but a shortcut for what the IDE does explicitly when you ask it to delegate to all methods of the field values.

I could go on to compare this with inheritance and how the result could be much the same, given interfaces, but more explicit and allowing fine grained, explicit "multiple inheritance", but this discussion must have happened already sometime in the past in some Java mailing list. Yet I could only find 15 year old links, for example on beust.com and citeseer describing ideas very similar to what I have in mind.

I think this is (a) really useful and (b) trivial to implement in a compiler, yet in 15 years nothing has appeared in Java.

So my question is:  What am I missing?  Is there a major hurdle in implementing this that I am not aware of?

As an aside: I would love to get good pointers to, for example, Java/JCP/JSR/whatever where this was discussed. I did not manage to find some.

As requested, let me try another example:

```<code>class FileWithMetas extends OutputStream implements Map<String,String> {
  final OutputStream out;
  delegate out.*; // takes care of "extend OutputStream"
  final Map<String,String> metas = new HashMap<>();
  delegate metas.*; // takes care of "implements Map"
  public FileWithMetas(...) {
    this.out = new FileOutputStream(...);
  }
  @Override //explicitly re-implement the delegated out.close()
  public void close() {
    //serialize the metas, for example
    out.close(); // with classic inheritance this would be super.close()
  }
}
</code>```

This will look very much like multiple inheritance in the end, but as mentioned: the delegation is just syntactic sugar replacing delegation methods generated by the IDE and except for slightly different error messages, the compiler should behave exactly like that. In fact I think this could replace inheritance completely (not that I am asking for it) --- given we keep interfaces, of course, which allow us to separate types from implementation.

答:
Your suggestion can't handle the delegation target being null which would go against everything Java is. If you try to handle this by forcing the object to be constant then it is just a less readable variant of multiple inheritance. By the way, multiple inheritance is already in Java 8.

Also you can easily get the same result by making the list public like this:

```<code>class ExtendedList<T>{
  const public List<T> values = new ArrayList<T>();
}
</code>```

Then you can use the same methods and when you want to use the interface just pass the List object directly.

Body:
Your suggestion can't handle the delegation target being null which would go against everything Java is. If you try to handle this by forcing the object to be constant then it is just a less readable variant of multiple inheritance. By the way, multiple inheritance is already in Java 8.

Also you can easily get the same result by making the list public like this:

class ExtendedList<T>{
  const public List<T> values = new ArrayList<T>();
}

Then you can use the same methods and when you want to use the interface just pass the List object directly.


问:
Affecting culture as a newly hired developer
I've been in my first professional position for about six months now, and so I am hitting what I suppose is the pretty typical moment:

Naievely perhaps, I think there's a lot of cultural baggage on the team that holds it back (A lack of respect for documentation work, hugely scattered documentation,  infrequent code review, a disconnect between development and test etc.)

I've started trying to make my mark; setting up tooling for documentation, static analysis, etc.

Where I am lost however is in the questions of buy in: While I can try to lead by example in some areas, I do need to get the team on board. I also have to consider that my priorities don't match those of the rest of the team.

How do I get buy in, and get a good feeling for what people value? Ideas I've considered:

Team survey -- Ask about what's important to drive future efforts

Skunkworks teams: Try to recruit small groups to work on driving forward pieces they care about in their 'free' time?

Try to convince management that we need to make these kinds of changes, and try to get them part of the review process?

Or maybe I need to STFU and keep my head down and do my work.

The team is about 50 people spread across multiple teams working on a shared C++ codebase.

答:
How big is the department you work in?

I recently implemented a set of standards for working with source control where I work since we used to have things like (a) cryptic messages which only the author and (maybe) the code reviewer understood, (b) monolithic commits which should be split into separate commits (e.g. 'changed comment', 'fixed bug', 'renamed method', etc.).

The way I did it was by:

Bringing it up with my managers in my annual review (your point 3).

Sending an email to the developers in my department saying I was writing a standard and asking to see if they had any suggestions/thoughts (your point 1).

After finishing the final draft, sending it out to ask the developers then asking for feedback.

Arranging a meeting for people to discuss openly any changes they thought might be beneficial (I bought a small box of chocolates to the meeting in order to sweeten the deal).

While it's not been a complete success, the way the department uses source control has definitely gotten better as a result (I think).

If I were you (and depending on how many people you have to influence), I'd talk to as many people as possible, let others know you're doing it (it might earn you brownie points with management for showing the initiative), and thoroughly research any changes you want to make: that way you can make others see why they should follow your suggestions.

edit: I should point out that there are about 15 developers in the department I work in.


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

答: "Right now, the usernames are required to be unique, and the passwords are not. Could we make it the other way around?"</p>


问:
TFS - My Work or Branch
My team has recently upgraded from VSS to TFS 2013.  In the past, there was a hard and fast "no checking in until the Item is complete," rule, but this is being challenging by a couple of newer team members, who have experience with Agile.

At the moment, I am working on a rather large change.  In the past, per our existing rule, I would not check in until it was fully complete (about two months' worth of work).  With TFS, we have some other options available, however, and we strive to get to an Agile process.  When talking about this with the team the other day, the two newer members were adamant that I just check in my changes (to the trunk, which is our dev branch).  My problem with this is that many of the files I changed are commonly modified in each release cycle.  If I check in before the feature is ready for release, and they then merge their changes with my changes, we can now not release either change until mine is ready.

The current solutions on the table for this problem are:

Create a branch specifically for this feature.  This does not mesh with our chosen branching strategy (code promotion), but is considered a special case.

Use a shelveset.  This way, at least my code is backed up on the server, and I can merge it all later when I am done.

Use My Work (honestly, I just found out about this feature a couple hours ago).  Same basic principle as a shelveset, though it seems to be "better practice."

Which of these (or perhaps #4?) is the best solution to our current problem?  We are aware that in general our processes have issues, and we are working on them, but it will take time to implement an actual Agile process in which the work is broken down such that checking in early and often is easy and causes zero issues.

答:
You may ask yourself why is it impossible to make a release until your changes are done.

In Agile projects, it is not uncommon to release several times per day, and still, some features may take days, weeks or months to be done. The usual approach is to have switches that enable or disable the pre-release feature during runtime, so that you, a developer, can run the feature, but ordinary users cannot.

In more complex systems, a similar switch has an additional benefit: it permits to test a feature with some users before enabling it for everyone. Those may be either users who are actively interested in features which are not yet available for general public (and accept the risk of bugs, information loss, etc.), or just a bunch of random users (miserably failing with a few thousand users is still better than with hundreds of thousands of users).

Of course, this forces you to commit code which compiles, and better be passing all the tests. This is not necessarily a drawback: as practice showed in the past, using nightly builds (which may happen more frequently than once per day, by the way) as a heartbeat of the project and trying to avoid getting a project into a state where it doesn't compile for weeks is beneficial for both the project and the team.

If it looks too difficult to work this way in your context, I would chose your first suggestion: a branch per feature with a merge to the trunk once the feature is finished, and maybe some merges between the branch and the trunk in the meantime.

Shelvesets have a different purpose. They are there to be able to store the current state of the project in order to work on a completely different stuff. For instance, you were implementing a two-hours feature when a critical bug was discovered in production and you should fix it right now. Shelvesets are second-class citizens. The major problem is that they integrate badly, if at all, with all the visualization and data mining tools for TFS. If somebody wants to know the progression of the team based on the information available in TFS, he may not be able to use shelvesets for that. Similarly, two-month commits would be too huge to be useful: how, for instance, would you diff a commit which changed half of the files of the code base, given that many files don't even look like their previous revisions?

As for My Work, unfortunately I'm unaware of this feature.

Title: TFS - My Work or Branch


答:
Ok, first step for me is to find out why/who else understands that this is an important issue. For example, if some manager halfway up your "chain of command" is hiding the fact that development work isn't done "to reliable standard", you could be in trouble if you expose this (obviously not in a GOOD company where managers listen to staff, but some companies are not good).

Second step is to find arguments for your project. Can you show that the code in the current project is suffering from bad discipline? For example, how many bugs are caused by lack of code-review.

(Of course, code review is not perfect either, I recently introduced a bug by moving a variable out from a loop [because I needed it in the context after the loop too], which led to the value not being set in an unusual condition -> bug detected in nightly testing.The code had been reviewed by two or three experienced engineers that didn't spot this...)

Third, can you show that the work will actually be more efficient "after these changes"?

If you can show these things, most managers will agree to introduce changes, because it improves productivity. But if you simply go into a manager and say "The work isn't very good here...", you may not get quite so far... :)

Title: Affecting culture as a newly hired developer

Body:
I've been in my first professional position for about six months now, and so I am hitting what I suppose is the pretty typical moment:

Naievely perhaps, I think there's a lot of cultural baggage on the team that holds it back (A lack of respect for documentation work, hugely scattered documentation,  infrequent code review, a disconnect between development and test etc.)

I've started trying to make my mark; setting up tooling for documentation, static analysis, etc.

Where I am lost however is in the questions of buy in: While I can try to lead by example in some areas, I do need to get the team on board. I also have to consider that my priorities don't match those of the rest of the team.

How do I get buy in, and get a good feeling for what people value? Ideas I've considered:

Team survey -- Ask about what's important to drive future efforts

Skunkworks teams: Try to recruit small groups to work on driving forward pieces they care about in their 'free' time?

Try to convince management that we need to make these kinds of changes, and try to get them part of the review process?

Or maybe I need to STFU and keep my head down and do my work.

The team is about 50 people spread across multiple teams working on a shared C++ codebase.