答:
disclaimer: I didn't check that any of the code in this answer actually compiles - it's only there to demonstrate a point.

I believe that the worst anti-pattern is Cargo Cult Programming - blindly following design patterns. I claim that it's much worse than any other anti-pattern, because while the other anti-pattern at least indicate some (wrong) thought process from the applier, Cargo Cult Programming shuts the mind down so it won't interrupt in the act of applying needless design patterns.

In our case, it seems like the Dependency Inversion pattern is being cargo-culted. Using DI for every class(save for data-only classes) is impossible, as at some point concrete classes are needed to be constructed. At the very least, some static methods and all factory classes should be exempted from this rule.

This exemption will make the task possible - but still needlessly hard. The key behind using Dependency Injection properly is understanding that you need to decouple modules(or components), not classes. Classes of the same module should be allowed to use other concrete classes of the same module. Of course - deciding where the boundaries between components go - which classes belong to each component - requires thought, something that is forbidden in cargo cults.

Another important thing is that some things are too small for can-be-used-by-interface-only, and some things are too high for the only-use-interfaces.

Your Math.Floor example is and example of "too small for can-be-used-by-interface-only". Inversing the dependency here will require something like:

```<code>interface IMath{
    public double Floor(double d);
}

public void Foo(IMath math){
    // ...
    double roundedAge=math.Floor(exactAge);
    // ...
}
</code>```

This allows us to do things like:

Call Foo with some other implementation of IMath that implements Floor differently

Mock IMath in unit tests - call Foo with an IMath object that doesn't really do the flooring, only pretends that it does.

You need to be very deep in the cargo cult to ignore the fact that these two benefits are completely useless here. It's hard to imagine a method that does Floor better than System.Math.Floor, and any attempt to mock it - unless it only works for specific cases - will be more complicated and error-prune than just doing the damn flooring.

Compare with the costs:

Having to send a IMath implementation to Foo.

Foo's implementation(using a concrete IMath object) is exposed by it's interface(requires an IMath object as argument).

Every method that uses Foo will also have these costs, since it can't use a concrete IMath directly.

and it's easy to see that it just ain't worth it in this case.
An example of "too high for the only-use-interfaces" is your Main method, which needs to actually create concrete objects that can't be injected to it.

Your StreamReader example is actually a good example for something that can possibly benefit from Dependency Inversion:

It's possible that you'll want to provide a different implementation of TextReader - for example one that reads and decrypts an encrypted stream.

It's possible that you'll want to mock TextReader in a unit test, so you wouldn't need an actual file to exist in a specific path when you run your unit test and can instead supply the text that would be read directly in the unit test.

Still - at some point a concrete object needs to be created. Here we should find a place that's "too high for the only-use-interfaces", where we can create the TextReader or a factory object that can create a TextReader and inject it down until it's used:

```<code>interface ITextReaderFactory{
    TextReader CreateTextReader(string path);
}

public void Bar(ITextReaderFactory textReaderFactory){
    // ...
    using(TextReader reader=textReaderFactory.CreateTextReader(path)){
        // do things
    }
    // ...
}

class StreamReaderFactory : ITextReaderFactory{
    public TextReader CreateTextReader(string path){
        return new StreamReader(path);
    }
}

public static void Main(string[] args){
    Bar(new StreamReaderFactory());
}
</code>```

Title: Classes shouldn't call other classes?

Body:
I've just finished reading The Art of Unit Testing, by Roy Osherove.  It was an interesting book, but I'm having trouble with something he mentions near the end (section 11.2.2):

Identifying "roles" in the application and abstracting them under interfaces is an
  important part of the design process. An abstract class shouldn’t call concrete classes,
  and concrete classes shouldn’t call concrete classes either, unless they’re data objects
  (objects holding data, with no behavior). This allows you to have multiple seams in
  the application where you could intervene and provide your own implementation.

Specifically, I don't understand what he means when he says that concrete classes shouldn't call concrete classes.  Consider the following examples in C#:

```<code>double roundedAge = Math.Floor(exactAge);
</code>```

Is this not considered a call to a class because Math.Floor is a static method?  Or is Osherove saying that the line of code above is bad design?  Another example:

```<code>using (StreamReader reader = new StreamReader(path))
{
    // do things
}
</code>```

Is this bad design due to the use of a StreamReader?  Or is this instance of StreamReader simply an object that holds data, as described in the quote above?

Rather than starting a discussion on whether or not it's bad practice to have classes call other classes, my goal here is to try and better understand what Osherove means in the passage I've quoted.  Does he really mean that the code in the two examples above should be avoided?  Thanks in advance for any replies.

EDIT: Below is an illustration from the book which is possibly elucidating.

Body:
disclaimer: I didn't check that any of the code in this answer actually compiles - it's only there to demonstrate a point.

I believe that the worst anti-pattern is Cargo Cult Programming - blindly following design patterns. I claim that it's much worse than any other anti-pattern, because while the other anti-pattern at least indicate some (wrong) thought process from the applier, Cargo Cult Programming shuts the mind down so it won't interrupt in the act of applying needless design patterns.

In our case, it seems like the Dependency Inversion pattern is being cargo-culted. Using DI for every class(save for data-only classes) is impossible, as at some point concrete classes are needed to be constructed. At the very least, some static methods and all factory classes should be exempted from this rule.

This exemption will make the task possible - but still needlessly hard. The key behind using Dependency Injection properly is understanding that you need to decouple modules(or components), not classes. Classes of the same module should be allowed to use other concrete classes of the same module. Of course - deciding where the boundaries between components go - which classes belong to each component - requires thought, something that is forbidden in cargo cults.

Another important thing is that some things are too small for can-be-used-by-interface-only, and some things are too high for the only-use-interfaces.

Your Math.Floor example is and example of "too small for can-be-used-by-interface-only". Inversing the dependency here will require something like:

interface IMath{
    public double Floor(double d);
}

public void Foo(IMath math){
    // ...
    double roundedAge=math.Floor(exactAge);
    // ...
}

This allows us to do things like:

Call Foo with some other implementation of IMath that implements Floor differently

Mock IMath in unit tests - call Foo with an IMath object that doesn't really do the flooring, only pretends that it does.

You need to be very deep in the cargo cult to ignore the fact that these two benefits are completely useless here. It's hard to imagine a method that does Floor better than System.Math.Floor, and any attempt to mock it - unless it only works for specific cases - will be more complicated and error-prune than just doing the damn flooring.

Compare with the costs:

Having to send a IMath implementation to Foo.

Foo's implementation(using a concrete IMath object) is exposed by it's interface(requires an IMath object as argument).

Every method that uses Foo will also have these costs, since it can't use a concrete IMath directly.

and it's easy to see that it just ain't worth it in this case.
An example of "too high for the only-use-interfaces" is your Main method, which needs to actually create concrete objects that can't be injected to it.

Your StreamReader example is actually a good example for something that can possibly benefit from Dependency Inversion:

It's possible that you'll want to provide a different implementation of TextReader - for example one that reads and decrypts an encrypted stream.

It's possible that you'll want to mock TextReader in a unit test, so you wouldn't need an actual file to exist in a specific path when you run your unit test and can instead supply the text that would be read directly in the unit test.

Still - at some point a concrete object needs to be created. Here we should find a place that's "too high for the only-use-interfaces", where we can create the TextReader or a factory object that can create a TextReader and inject it down until it's used:

interface ITextReaderFactory{
    TextReader CreateTextReader(string path);
}

public void Bar(ITextReaderFactory textReaderFactory){
    // ...
    using(TextReader reader=textReaderFactory.CreateTextReader(path)){
        // do things
    }
    // ...
}

class StreamReaderFactory : ITextReaderFactory{
    public TextReader CreateTextReader(string path){
        return new StreamReader(path);
    }
}

public static void Main(string[] args){
    Bar(new StreamReaderFactory());
}


问:
Enforcing coding standards: What are the trade-offs of different methods?
Our team has recently agreed on some very light coding standards, and that we need a means of enforcing them. We already have a mature Continuous Integration practice including frequent, small check-ins and pre-tested commits.

We're considering two methods for implementing an enforcement mechanism: a pre-commit SVN hook, or a dedicated build configuration on the CI server. Here's the trade-offs we've considered so far:

An SVN hook ...

(-) requires SVN server admin privileges to setup, which we don't have. We can work with IT, but avoiding the overhead is nice.

(-) points to a script, which we'd like to keep under version control with the rest of the product. I don't immediately know how to point at the correct hook-script, taking into account branches, tags, and trunk work.

(-) requires more work for reporting. The script would need to handle both generating and publishing the report.

(+) gives quick feedback.

(+/-) provides hard enforcement: the code checks-in, or it doesn't . Usually a good thing (it's called "enforcement" for a reason), but may give false positives.

The CI build configuration ...

(-) consumes time on both the CI server and an agent. Might be trivial, but does add up.

(-) introduces some extra latency, making feedback less immediate.

(+) easily handles standards that evolve over time, by pointing to the version of the script that exists in whichever branch we're working on.

(+) provides easier reporting. We already use the CI system for other reports. Adding a new one would be straight-forward.

(+) configurable enforcement: easier to soften the requirements, if necessary. We could collect a list of violations to fix out-of-band, or provide warnings about standards we're adopting on a trial basis.

What are the trade-offs of these different methods in enforcing coding standards here?

Related: Should coding standards be enforced by the CI server? - Raises some good points, but doesn't consider SVN hooks.

答:
You have missed one more option, execute the enforcement of coding standards at compile time (if you are working with a compiled language) or from your development environment (if you have one). That way the developers get immediate feedback regarding their violations of the coding standards. At first most developers will find it annoying, but they will soon get used to it (I did) and start coding in the right style, thereby not making violations of the coding standards anymore.

Obviously you'll also need to verify this somewhere else to make sure that nothing slips by. I would prefer to use the build server for this because

No necessary changes to the version control system, thus not slowing down commits etc.

Still have the ability to commit code even if it's not technically correct so it is possible to commit code to branches for safe keeping or experiments.

The CI build is used to notify developers all kinds of errors, an extra type of error is not too unexpected. Having the errors come from the commit however would seem to be unexpected(?).

Finally if you use the SVN hooks think about this, the SVN hooks might not allow you to check in code that violates the coding style but you can still commit code that is broken. That somehow seems backwards to me given that you should probably care more about code that doesn't compile or run than about code that violates the coding standards.

ContentLicense: CC BY-SA 3.0


问:
Sharing on Github
Over the past couple weeks I have gotten a lot of help from StackOverflow users on a project, and rather than keep the finished product to myself I wanted to share it unencumbered by licenses, but don't want there to be so much legwork during installation that users shy away from trying it.

I am about to post it to Github and choosing public domain licensing. I would like to to be super simple for users to make use of and just FTP it up and go.

That being said, do I need to make sure I remove things like the JQuery file, and other GPL / MIT licensed dependencies that I didn't write but that my code depends on? I haven't removed any copyright notices from the other code and all of it open source, it would just be nice if users could download everything at once while of course not trying to represent that I am the license holder of the dependencies.

Inside my files are also some snippets, do those have to be externalized with installation instructions or can it be posted as is? Here is an example, my nav.php file is 115 lines long and I have these at the top:

```<code><script type="text/javascript" src="./js/ddaccordion.js">
/***********************************************
* Accordion Content script- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* Visit http://www.dynamicDrive.com for hundreds of DHTML scripts
* This notice must stay intact for legal use
***********************************************/
</script>
<link href="css/admin.css" rel="stylesheet">
<script type="text/javascript">
    ddaccordion.init({
    headerclass: "submenuheader", //Shared CSS class name of headers group
    contentclass: "submenu", //Shared CSS class name of contents group
    revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
    mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
    collapseprev: false, //Collapse previous content (so only one open at any time)? true/false
    defaultexpanded: [], //index of content(s) open by default [index1, index2, etc] [] denotes no content
    onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
    animatedefault: false, //Should contents open by default be animated into view?
    persiststate: true, //persist state of opened contents within browser session?
    toggleclass: ["", ""], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
    togglehtml: ["suffix", "<img src='./images/plus.gif' class='statusicon' />", "<img src='./images/minus.gif' class='statusicon' />"], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
    animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
    oninit:function(headers, expandedindices){ //custom code to run when headers have initalized
        //do nothing
    },
    onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
        //do nothing
    }
})
</script>
</code>```

答:
I'm not a lawyer, but if your project depends on a single thing that's licensed under GPL then your entire project must be licensed under GPL. At this point, it doesn't really matter license-wise if you keep the licensed open-source files in the repo.

That was the legal side(again - I'm not a lawyer). From the technical side, you should try using a dependency manager - or at least Git Submodules - for those files. These will allow you to avoid storing those external files in your repository, make upgrading them to newer versions easier, and gives you control over which versions to use in your project. Those things introduce the work overhead of the initial configuration, but once you do that it's super easy to use them for adding more dependencies, so if you have many dependency it's worth the extra work of setting it up.

Title: Sharing on Github


问:
How to enforce implementation of interface to behave a certain way
Suppose you had the following interface

```<code>public interface IUserRepository
{
    User GetByID(int userID);
}
</code>```

How would you enforce implementers of this interface to throw an exception if a user is not found?

I suspect it's not possible to do with code alone, so how would you enforce implementers to implement the intended behavior?  Be it through code, documentation, etc.?

In this example, the concrete implementation is expected to throw a UserNotFoundException

```<code>public class SomeClass
{
    private readonly IUserRepository _userRepository;

    public SomeClass(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public void DisplayUser()
    {
        try
        {
            var user = _userRepository.GetByID(5);
            MessageBox.Show("Hello " + user.Name);
        }
        catch (UserNotFoundException)
        {
            MessageBox.Show("User not found");
        }
    }
}
</code>```

答: There's no way to 100% force the behavior you want, but using code contracts you could say that implementations must not return null, and perhaps that the User object has the id passed in (so an object with userid 0 would fail if 1 was passed).  On top of that, documenting what you expect of implementations might help as well.</p>


问:
How to handle fine grained field-based ACL permissions in a RESTful service?
I've been trying to design a RESTful API and have had most of my questions answered, but there is one aspect of permissions that I'm struggling with.

Different roles may have different permissions and different representations of a resource. For example, an Admin or the user himself may see more fields in his own User representation vs another less-privileged user. This is achieved simply by changing the representation on the backend, ie: deciding whether or not to include those fields.

Additionally, some actions may be taken on a resource by some users and not by others. This is achieved by deciding whether or not to include those action items as links, eg: edit and delete links. A user who does not have edit permissions will not have an edit link.

That covers nearly all of my permission use cases, but there is one that I've not quite figured out. There are some scenarios whereby for a given representation of an object, all fields are visible for two or more roles, but only a subset of those roles my edit certain fields.

An example:

```<code>{
    "person": {
        "id": 1,
        "name": "Bob",
        "age": 25,
        "occupation": "software developer",
        "phone": "555-555-5555",
        "description": "Could use some sunlight.."
    }
}
</code>```

Given 3 users: an Admin, a regular User, and Bob himself (also a regular User), I need to be able to convey to the front end that:

Admins may edit all fields, Bob himself may edit all fields, but a regular User, while they can view all fields, can only edit the description field. I certainly don't want the client to have to make the determination (or even, for that matter, to have any notion of the roles involved) but I do need a way for the backend to convey to the client which fields are editable.

I can't simply use a combination of representation (the fields returned for viewing) and links (whether or not an edit link is availble) in this scenario since it's more finely grained.

Has anyone solved this elegantly without adding the logic directly to the client?

答:
Another option is to have another resource (i.e. /permissions/userResource/user/1) that will return fields that user is allowed to modify or view.

```<code>{

read: [id,name,age,occupation,etc],

write: [description]

}
</code>```

I think this is similar to above suggestion.

Body:
Another option is to have another resource (i.e. /permissions/userResource/user/1) that will return fields that user is allowed to modify or view.

{

read: [id,name,age,occupation,etc],

write: [description]

}

I think this is similar to above suggestion.


问:
Pair Programming/Collaboration in a small company
I work at a small development company as the lead developer. We have two other developers, as well as my boss who is a developer, but doesn't really do much of the actual coding anymore.

The problem I am trying to overcome is multifaceted. We have a tendency all to work on our own projects without much collaboration between us. As a matter of fact, I (as the most advanced developer) ask for the others' opinion/help more than they do mine, because I value the input of an outside eye.

I want to increase our collaboration, and have expressed that to them. In large part because I'd like to show them some things about how to become better developers and follow better practices. But given our other developers' personality types, I think they are more comfortable working alone.

I've been reading about pair programming, and I have read (in some forums) that it doesn't work well when you have one developer being more advanced than the others (which I am). And yet, I feel it is imperative that we start to collaborate so that our work is not so disparate.

My question is whether anyone has ever been in a similar situation, and what worked for them?

I realize this is not a one-size-fits-all situation, but I'm willing to give multiple approaches a shot.

We all work in a common area, developers don't have have individual offices / cubicles.

答:
Some months after raising this question, I have to say I'm happy with our results. But it is not exactly the one I accepted in the beginning. Keep in mind this is small team, so this solution will not fit everyone one.

I've found it's best to let everyone do their own work. And over time we have developed a trust in one another where if we run in to a problem, we call the others to our aid. I don't think anyone wants to work with someone watching over their shoulder. I occasionally sit behind someone and sometimes help them through a problem without being solicited. Sometimes I have nothing to add, and I maybe annoy them a bit. But they understand that I'm not there to harp on them. I'm mostly there to take a break from what I'm doing and introduce a bit of collaboration.

What I've found is that the RIGHT people over time (in a small team) pick up and synchronize with that others are doing. There's no need to micro manage or tell someone what they are doing wrong all the time.

From time to time, sit down with someone and work through a problem, whither you are an expert or someone learning, or both. Explain why you would or wouldn't do something one way as opposed to another. Good ideas catch on usually, while others get left behind. And at the end of the day you have a productive, cohesive group of people who may be working on different things but share a common purpose.


问:
Why don't more languages have the ability to compare a value to more than one other value?
Consider the following:

```<code>if(a == b or c)
</code>```

In most languages, this would need to be written as:

```<code>if(a == b or a == c)
</code>```

which is slightly cumbersome and repeats information.

I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea.

Why don't more languages offer it? Is there performance or syntax issues?

答:
You ask why can't we do this: if(a == b or c)

Python does this very efficiently, in fact, most efficiently with set:

```<code>if a in set([b, c]):
    then_do_this()
</code>```

For membership testing, 'set' checks that the element's hashes are the same and only then compares for equality, so the elements, b and c, must be hashable, otherwise a list directly compares for equality:

```<code>if a in [b, c]:
    then_do_this()
</code>```

Body:
You ask why can't we do this: if(a == b or c)

Python does this very efficiently, in fact, most efficiently with set:

if a in set([b, c]):
    then_do_this()

For membership testing, 'set' checks that the element's hashes are the same and only then compares for equality, so the elements, b and c, must be hashable, otherwise a list directly compares for equality:

if a in [b, c]:
    then_do_this()


问:
Reflecting on finished project with no other technical criticisms?
I'm a coop (in college but I work 3 months, then do classes for 3 months, work again for 3 months, etc until I graduate) at a company in their IT department. My job usually has to do with writing software but we are not a software company and much of the software that is is written in India. This work term (3 months) I was given a large project, to design some software to visualize data pulled from another one of our systems.

I ended up at the end of this term with two pieces of software for, one 100% done (the data pulling back end) and the other 80% done (the graphical front end). I had fun and learned a lot as always, but I'm not too happy with the results code wise. I have never gotten a chance for a code review or a chance to do any learning about design and analysis strategies for the reason I mention above in the year that I've been here (4 terms).

Here's how the project went, and it reflects how I have done pretty much every project to date, although it's more clear in this project as this is the biggest thing I've done so far. The first thing I did was diagram out how the whole system would operate from a high level. I don't usually do this but I was asked to by my boss. Then, I dove right into the problem and start banging away. To me, I find that it helps (and is more fun at the same time) to get something down and working to revise for organization shortly after so that I can continue in an organized fashion. From there the building slowed down a bit as the project got bigger. I would get more confused but also start diagramming more things out first, stopping to think about how what I'm currently building will fit into the entire system. This continued on for a while until my 3 month term was almost up. Here, I started rushing to get things done. I started destroying some of the organization in favor of quick things so that I could get a working prototype (I was only asked for a prototype so I figured this was alright and if the project went forward I could always revise it). This is where my entire thing started to fall apart as I didn't really have time to properly think through how a lot of what I was coding would affect everything else. I feel like now, at the final stage, I have a lot a mix of loosely and tightly coupled code with a barely working prototype.

In hindsight, here's what I see:

I did a good job on the original overview and it helped me too because I could break down the entire thing into a few main chunks. Problems started to arise when I got into specifics of each chunk. There was a good set idea on what each piece would do, but not the specific parts that made that piece work (I don't know what I could have done more though to explain each piece though. I find when it comes down to specifics like this, I find out as I go).

There were many things about the system that I was pulling data from that I did not know at the very start and I should have gotten a lot more insight onto how the system works as a whole. However, at the start of the term I'm always shy and tend to not ask questions. This probably also contributed to why I usually don't know the specifics of each piece until I'm actually doing them.

I was also a victim of a bit of scope creep as few features were added to the todo list with about a month and a half to go.

I never seem to know exactly where I want to go on specific parts. I try something and if that doesn't work, I try something else until it works or I get something that's neater. Is this the right way to do things?

My questions:

What could I have done better? I know no one here will know the specifics of my project but there's no one else with coding knowledge who could tell me how I could grow in this situation.

How could I review myself better? Since I never really have anyone else reviewing my coding and I'm not working with any other coders directly, how could I have reflected better on my own project, both after, and during the project?

The question about what I could do better is directed mainly at the bolded portions of my explanation where I feel most concerned about how I approached the problem.

答:
Welcome to just about every project ever. What you've described is actually quite normal in the industry, even on team projects. You know the most about the project domain at the end of the project, so looking back you can usually find things that could have been done better. And as pressures to meet deadlines loom, you often have to make compromises. Both of these ideas fall into a category known as "technical debt."

The fact that you've reflected on this and even asked this question shows that you're wanting to learn and improve. That's a great trait that if kept up will yield the experience which over time answers your questions of "What could I have done better?" and "How could I review myself better?"

All the best developers I know are the types that constantly try to refine their skills. They're the types that usually look back at code from months ago and think, "Yikes, why did I make such a mess." (Though they also have a few polished gems that stand the test of time.)

Going forward, I'd suggest:

Keep trying, and keep reviewing yourself.

Learn about coding patterns that help with these types of situations.

Research which software development methodologies and processes will help you keep a project under control.

Look for opportunities to collaborate with others on a project so you can learn from them.

Find a good balance between iterating to improve code vs. calling it "good enough" to be done.


问:
Implementing Generic Routines
Is it possible to implement generic routines in any language (C#, Java, etc). By generic routines I mean, in specific event Handlers. Lets say, I have 2 Buttons and 2 text boxes. One Button, when pressed, takes the first text box text and converts to Uppercase and second button prints the length of the string in the other text box. Now, Can I have a function as

```<code>button(type, textbox) {
if(type==1)
/*Convert to upper case*/
else if(type==2)
/*Print the length*/
}
</code>```

The type takes any button as input and further processes it. I want to implement this because of redundancy in my code and I want to make my code portable to other languages. So that I need to modify only the syntax to make it work. Is it feasible?

答:
In C#, it would look something like this:

```<code>// Loop through the controls on the form, and do something
// specific with each control, based on its type.
foreach (Control control in form.Controls)
{
    switch (control.GetType().Name)
    {
        case "TextBox":
            var textBox = (TextBox)control;
            // Do something with the text box
            break;
        case "ComboBox":
            var comboBox = (ComboBox)control;
            // Do something with the combo box
            break;
        case "CheckBox":
            var checkBox = (CheckBox)control;
            // Do something with the checkbox
            break;
    }
}
</code>```

This code works because all Controls in Winforms inherit from a base Control class.

Title: Implementing Generic Routines

Body:
In C#, it would look something like this:

// Loop through the controls on the form, and do something
// specific with each control, based on its type.
foreach (Control control in form.Controls)
{
    switch (control.GetType().Name)
    {
        case "TextBox":
            var textBox = (TextBox)control;
            // Do something with the text box
            break;
        case "ComboBox":
            var comboBox = (ComboBox)control;
            // Do something with the combo box
            break;
        case "CheckBox":
            var checkBox = (CheckBox)control;
            // Do something with the checkbox
            break;
    }
}

This code works because all Controls in Winforms inherit from a base Control class.


问:
What is the point of a Gantt Chart, and will it help me?
My (non-technical) colleague has threatened me with a Gantt chart for a new project that we are currently planning.  What is this likely to provide for us, and will it be a helpful tool?</p>

答:
No single invention deserves more credit for making project planning as unpopular as it is today than Tracking Gantts. Tracking Gantts should not only be considered harmful - they should be considered evil. Here's why.

Reason #1: Their motivation

Tracking Gantts let you see, for each step of your plan, how long you thought it's going to take and how long it's actually taking. You get to know, every day and in status meeting, that phase X was supposed to start by March, but it's clearly not going to get started until May.
Awesome.
You already knew, when you did initial planning, that the plan is going to have to change as the project progresses. New information comes to light. People and resources are unpredictable, etc. So why is it important to constantly be reminded, in every status meeting, how poorly your early predictions are fairing in real life?

Reason #2: They force you to stick to the original plan

The very idea of tracking a project's Gantt chart means that instead of focusing on constantly adapting your work plan based on new information, you choose to stick to an outdated plan, just because it lets you point fingers and highlight the mis-predictions that were the inevitable result of the huge amount of uncertainty that the early planning phase of the project entailed. After all, you can't track the Gantt if you allow the plan to change radically, right? It has to have the same general shape and be comprised of the same steps, otherwise there's nothing to track...
Boneheaded sticking to plans is the number-one reason why "Waterfall" is actually considered a pejorative term these days. Planning ahead is confused with sticking to the original plan.

Reason #3: They teach you nothing

It's not like the delay in this project is actually going to change the way you plan the next project, unless the projects you're planning are predictably similar and repetitive. After all, that's what Gantts were initially used for - planning work in factory production lines, where tasks are very well defined and their duration is extremely predictable.

The value that tracking adds to a software development Gantt chart is zero. Arguably even less than zero. Not only are past estimations irrelevant for new projects, the illusion that you can actually improve your estimation ability over time by retrospection is dangerous. Sure, a CS student might really not know that integration takes lots of time in real life. But anyone that's been involved in more than two projects in their lifetime is already well aware of the usual suspects for delayed projects. The real reason projects are delayed is not some mathematical error factor that must be applied to estimations in general - it is the inherent uncertainty that comes with doing something for the first time and not knowing exactly how it's going to pan out.

There are actually project management systems out there that try to attack the problem from this misguided angle. They measure your predictions vs. actual performance and try to correct your overall estimation using statistical analysis. As if "Danny always underestimates everything by 14.3%" is ever the case. Danny isn't stupid, and to assume that the error of his predictions is predictable is indeed idiotic. It confuses the primitive "cure" - adding factors to your estimation - with the cause of the problem. Your estimation isn't inaccurate because it wasn't multiplied by the "correct" factor. Your plan is simply incomplete; and every plan is incomplete in its own way.

Reason #4: They focus your attention on the wrong things

Instead of being focused on what needs to get done to deliver on time, you're now focused on justifying your inaccurate predictions. Instead of focusing on planning in more detail and adapting your plan to new information, you're rehashing an outdated plan. Projects are seldom delayed because the work-plan's parts were incorrectly estimated. They're delayed because a crap-load of things were simply left out of the original plan. Tracking Gantts make this even worse, because what sort of motivation do you have to insert more detail into your plan if it's all just going to wind up highlighted as a poor estimations in every status meeting? They make you stick to large, track-able chunks of work in your Gantt chart. Instead of letting you focus on adaptation and getting on the right track, they make you reexamine irrelevant decisions that were made when less information was available.

There's also the problem of not having good enough tools to manage sufficiently elaborate plans. You have a much better chance at constructing a good initial plan (and estimation) if your tools allow you to expose all those frequently neglected steps along the way. Traditional Gantts are low-resolution beasts that are rightfully seen by developers as caricatures of the reality of project management. What's needed is a tool that makes it easy to add as much information as possible to the work plan at the earliest stage, and then make it just as easy to adapt your plan as the fog of uncertainty slowly fades away from over your project. The last thing you need is incessant low-resolution reminders of your inaccurate past predictions. Tracking Gantts are good for pointing fingers and covering asses, not for getting things done.

ContentLicense: CC BY-SA 2.5


答:
APL-style languages allow you to compare a scalar with each element in a vector in a single operation. This produces a Boolean vector. For an example, I'd like to shamelessly promote my minimally-featured apl calculator, inca (online interpreter).

```<code>   a<5
5
   b<4
4
   c<5
5
   a=b c
0 1
</code>```

To reduce this to a single value, we can do an inclusive or by summing and checking for nonzero.

```<code>   0!+/a=b c
1
   c<6
6
   0!+/a=b c
0
</code>```

So, as the other answers say, the issue is syntax. To some extent, syntax solutions have been found, at the perhaps heavy cost of learning the array paradigm.

Title: Why don't more languages have the ability to compare a value to more than one other value?

Body:
Consider the following:

```<code>if(a == b or c)
</code>```

In most languages, this would need to be written as:

```<code>if(a == b or a == c)
</code>```

which is slightly cumbersome and repeats information.

I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea.

Why don't more languages offer it? Is there performance or syntax issues?

Body:
APL-style languages allow you to compare a scalar with each element in a vector in a single operation. This produces a Boolean vector. For an example, I'd like to shamelessly promote my minimally-featured apl calculator, inca (online interpreter).

   a<5
5
   b<4
4
   c<5
5
   a=b c
0 1

To reduce this to a single value, we can do an inclusive or by summing and checking for nonzero.

   0!+/a=b c
1
   c<6
6
   0!+/a=b c
0

So, as the other answers say, the issue is syntax. To some extent, syntax solutions have been found, at the perhaps heavy cost of learning the array paradigm.


答:
Normally, this should be done by having one handler for each logic.

```<code>void handleUppercase(object sender, EventArgs args)
{
    // convert text to uppercase
}

void handleLength(object sender, EventArgs args)
{
    // display length
}

// then assign those handlers properly
button1.OnClick += handleUppercase
button2.OnClick += handleLength
</code>```

Also, you are not going to have much luck changing code for different languages, because different languages use different UI frameworks. And there are too big differences between those frameworks to allow any kind of sharing. If you want to have same code in different languages, you have to make sure it doesn't depend on any specific framework. Which UI frameworks are.

The case is quite different when you have same logic, but on different buttons with different parameters. In this case, you have 2 basic options.

First is to use similar approach as Robert suggests:

```<code>void handleUppercase(object sender, EventArgs args)
{
    if (sender == buttonA) // do logic for first arguments
    if (sender == buttonB) // do logic for second arguments
}
buttonA.OnClick += handleUppercase
buttonB.OnClick += handleUppercase
</code>```

Second option is to parametrize the handler itself. In OOP, that could be done if the handler was a Command. Simply create different instances of command with different parameters for each button. In functional way, you could use partial application. But because C# doesn't have this concept, you have to help yourself with lambdas:

```<code>void handleUppercase(object sender, EventArgs evArgs, Argument arg)
{
    // do logic for arg
}

buttonA.OnClick += (s, e) => { handleUppercase(s, e, arg1); }
buttonB.OnClick += (s, e) => { handleUppercase(s, e, arg2); }
</code>```

Title: Implementing Generic Routines

Body:
Is it possible to implement generic routines in any language (C#, Java, etc). By generic routines I mean, in specific event Handlers. Lets say, I have 2 Buttons and 2 text boxes. One Button, when pressed, takes the first text box text and converts to Uppercase and second button prints the length of the string in the other text box. Now, Can I have a function as

```<code>button(type, textbox) {
if(type==1)
/*Convert to upper case*/
else if(type==2)
/*Print the length*/
}
</code>```

The type takes any button as input and further processes it. I want to implement this because of redundancy in my code and I want to make my code portable to other languages. So that I need to modify only the syntax to make it work. Is it feasible?

Body:
Normally, this should be done by having one handler for each logic.

void handleUppercase(object sender, EventArgs args)
{
    // convert text to uppercase
}

void handleLength(object sender, EventArgs args)
{
    // display length
}

// then assign those handlers properly
button1.OnClick += handleUppercase
button2.OnClick += handleLength

Also, you are not going to have much luck changing code for different languages, because different languages use different UI frameworks. And there are too big differences between those frameworks to allow any kind of sharing. If you want to have same code in different languages, you have to make sure it doesn't depend on any specific framework. Which UI frameworks are.

The case is quite different when you have same logic, but on different buttons with different parameters. In this case, you have 2 basic options.

First is to use similar approach as Robert suggests:

void handleUppercase(object sender, EventArgs args)
{
    if (sender == buttonA) // do logic for first arguments
    if (sender == buttonB) // do logic for second arguments
}
buttonA.OnClick += handleUppercase
buttonB.OnClick += handleUppercase

Second option is to parametrize the handler itself. In OOP, that could be done if the handler was a Command. Simply create different instances of command with different parameters for each button. In functional way, you could use partial application. But because C# doesn't have this concept, you have to help yourself with lambdas:

void handleUppercase(object sender, EventArgs evArgs, Argument arg)
{
    // do logic for arg
}

buttonA.OnClick += (s, e) => { handleUppercase(s, e, arg1); }
buttonB.OnClick += (s, e) => { handleUppercase(s, e, arg2); }


问:
What happens when both heap and stack are full?
Suppose I am using a very heavy applications(or you can say that it is a very bad code which keeps on allocating memory on heap and won't free it and also uses recursion) Now after some point of time both heap and stack will have no space to expand.

Now In this situation heap and stack don't have any free space in between them and if I try to allocate some memory on heap then what will happen? will it overflow over stack?

And also what happens if we make a recursive call and stack needs to expand then will it overflow over heap?

答: The system will detect this and cause an error. Older languages just simply crash the program. Newer languages generally throw an exception. But handling those exceptions might be problematic, because there is not enough memory or stack for it.</p>


问:
Are the following Use Case Levels determined correctly?
I am confused about use case levels. All I could understand was that use cases that are contained in another use case fall under the level which is below the level of the container use case.

I have identified the following use cases for an e-commerce store and I would like to know if their levels are correctly determined or not. Please provide a description of the differences between levels if I have done something wrong here.

答:
There is no single "correct" way of writing and structuring use cases. First and foremost, your approach has to work for you and the people you work with.

I'd like to suggest that "login" is often not a 'real' user goal, thus I'd see this as below the user goal level. From my perspective, "buy products" seems to be a reasonable user goal for a Customer in your example. "Browse products" might not always be a primary user goal, e.g. when you're browsing through a catalog in order to buy something. On the other hand, the Customer might just want to obtain information without having the intent to buy immediately.

Alistair Cockburn's "Writing Effective Use Cases" is certainly a great source on use case writing. I also suggest looking at "Lean Architecture for Agile Software Development" by James Coplien and Getrud Bjornvig: this book discusses the idea of a "habit", i.e. a sequence of tasks that comes up in the context of different use cases but that is in itself not a fully fledged use case. (Search "use cases habits" and you'll find a relevant section of the book. Then go buy and read the book -- it's great!)

Decomposing use cases into ever smaller use cases is a hotly debated topic with many people being fairly reluctant to do so. Among other issues, the administrative overhead of keeping track of use cases dependencies and keeping related use cases in synch can be very high. Also, fine-grained, highly decomposed use cases are often difficult to work with for non-IT people (and, truth be told, also for IT folks).

Best regards,
Oliver


答:
In some (popular) languages == operator is not transitive. For instance in JavaScript 0 is equal to both '' and '0', but then '' and '0' are not equal to eachother. More of such quirks in PHP.

It means that a == b == c would add another ambiguity, because it could yield a different result depending on whether it's interpreted as (a == b) & (a == c) or (a == b) & (a == c) & (b == c).


问:
variable overwriting in PHP
For example I have this code:

```<code>$route = 'product/category';

//variable overload
$type  = explode('/',$route);
$type  = $type[1];
</code>```

My thinking behind this is that I actually don't need unique variable name for exploded variable, so why not to overwrite?

Is this really bad concept? Or is there some more elegant way to write this?

答:
No, it's absolutely not bad. All you're doing here is assigning a new value to a variable. It has no special name.

As for more elegantly writing it, you could write the following as of PHP 5.4:
$type = explode("/", $route)[0];

Title: variable overwriting in PHP


问:
Alternatives to null values and option-like types
Related to this question i want to know if there is a concise way to eleminate null values out of code in general or if there is not.

E.g. imagine a class that represents a user with birthday as attribute which can be set but does not have to, which then means it's null. In scala and similar languages one could use the Option type to describe this and i see why this is better then just having a regular null value as one would code it in java.

However i wonder if this is the right concept or if we can do it better in this case and even in general.

I came to the idea that we could replace the users birthday (and other optional or possibly unknown/unset attributes) with a list of possible optional attributes. So we could have like

```<code>ourUser.getOptionalAttributes()
// could return a list [Date Birthday, Float Height, Color Eyecolor]
// or just [Color Eyecolor]
// or even an empty list
</code>```

However using a regular list would mean that we could store multiple birthdays e.g.
So we needed a way to tell the compiler that the list may only contain one Birthday type.

Am i totally on the wrong track here and are option types the (philosophical) correct way to express optional attributes?
Also, are there additional concepts for handling the logic of optional attributes other than nullable types and option-like types?

答:
I believe it's a question of what type of question you would like to pose in
the end. Lets say you just want all related information to show up whenever
you show someone the user. Then a list (or EnumMap, if you want to make some uniqueness guarantees) would be nice since you just want to iterate over it
and print the stuff.

However, if you want to ask questions like "if this user have a birthday show
a notice 1 day in advance to friends" then even if you start of with the list
you are left with a Option in the end. I don't think this is bad, but it
doesn't free you from the idea of optional values.

-edit-

A drawback is that you have to fit all your data into the same type. Might
be easy or difficult depending on your requirements.


问:
How to deal with a misnamed function in production code?
I've recently come across a Python library on GitHub. The library is great, but contains one glaring typo in a function name. Let's call it dummy_fuction() while it should be dummy_function(). This function is definitely "in the wild" and most likely used in embedded systems.

The first thing that springs to mind is to add a second version of the function with the correct name and add a deprecation warning to the first version for the next release.

Three questions:

Could the approach above have any unintended consequences?

Is there a standard approach to this kind of problem?

How long should any deprecation warning be left in place?

答:
First and foremost, the policy depends on the maintainer.

I think your question is interesting, but mostly opinion-based.

In my personal opinion your approach is sound - rename the function and leave the misspelled version as a deprecated artifact, redirecting to the correct one.

Could the approach above have any unintended consequences?

It could break the code eg. if someone couldn't stand the misspelling either and implemented a renamed version of their own. Now there'll be a name clash once they update the library.

Is there a standard approach to this kind of problem?

Don't make spelling mistakes when writing a library ;)

How long should any deprecation warning be left in place?

I believe the deprecation should be left in place until the next major release (when the first digit in version number is increased).

This is when some - justified - backward compatibility breaking is tolerable, and it's up to the library users to ensure their code still builds fine.

Just make sure to point it out in the changelog: guys, if you used dummy_fuction, replace it with dummy_function everywhere and you're good to go.

If the library isn't versioned, as it might be - it makes a good case to start versioning it.


问:
As an interviewer, asking a candidate to find errors in small sample code. Is this fair?
We've been interviewing on and off for about two years, and I've run this by about 30 candidates. I wrote some 20 lines of code which perform a relatively basic operation, but has a bunch of errors in it. None of them are syntax errors. Errors range from bad memory management, incorrect data types, multithreading problems, misuse of keywords, and a couple functional errors that would give undesired output.

People get really nervous during this question. Is it a fair question to be asking? The goal is to get an idea of their comfort level with the language (Objective C has some very strange behaviors, and most applicants we get are relatively inexperienced in ObjC specifically as compared to other languages), as well as see their ability to recognize logical problems in otherwise foreign code.

Once a candidate has made a first pass, I often will point to specific lines that have remaining errors on them and see how much hand-holding it takes to get a correct identification and/or fix from them.

At our company, this is a real world scenario, as programmers would be thrust straight into a 100k line app and given bugs to fix, and we need people that are comfortable with working with the code of 6 other programmers.

However, today, another of our interviewers told me he hated this problem (I didn't quite understand what his reason was, admittedly). Is this something I should continue asking, or should I look for alternate avenues?

答:
As an aside, I'd be interested to hear why the other interviewer thought the problem was inherently unfair, but on to the meat of your question:

It rather depends on what you're trying to achieve. If your goal is to recruit an Objective C guru, then the test is clearly fair.

However, if you're just looking for a journeyman Objective C programmer then perhaps not. Is the code typical of what they'll find in your organisation or purely an academic exercise? Certain types of code problems sometimes vary from organisation to organisation.

Also, how the test is staged could be a factor:

Are they told how many issues are in the code?

Are they timed?

Are the interviewers sat in the room or are they left alone?

Are they allowed to ask questions?

Whilst you point out that they'll be expected to fix such problems day to day, they won't be doing this from a source code print out.

The acid test of course is whether you're getting the right sort of staff once they jump through the hoop. If you are, then I'd be inclined to stick with it.


答:
are option types the (philosophical) correct way to express optional attributes?

The repeated word suggests that yes, they are. They simply and clearly express what you're trying to express.

There is one null-alternative that you haven't mentioned, and can often be better than a traditional null or Option. The Null Object Pattern, where you define an object with neutral default behaviour, so that calls to it do nothing transparently. An empty collection can be considered a null object, but the concept can be applied in other places too.

Title: Alternatives to null values and option-like types

Body:
Related to this question i want to know if there is a concise way to eleminate null values out of code in general or if there is not.

E.g. imagine a class that represents a user with birthday as attribute which can be set but does not have to, which then means it's null. In scala and similar languages one could use the Option type to describe this and i see why this is better then just having a regular null value as one would code it in java.

However i wonder if this is the right concept or if we can do it better in this case and even in general.

I came to the idea that we could replace the users birthday (and other optional or possibly unknown/unset attributes) with a list of possible optional attributes. So we could have like

```<code>ourUser.getOptionalAttributes()
// could return a list [Date Birthday, Float Height, Color Eyecolor]
// or just [Color Eyecolor]
// or even an empty list
</code>```

However using a regular list would mean that we could store multiple birthdays e.g.
So we needed a way to tell the compiler that the list may only contain one Birthday type.

Am i totally on the wrong track here and are option types the (philosophical) correct way to express optional attributes?
Also, are there additional concepts for handling the logic of optional attributes other than nullable types and option-like types?


问:
Opposite term of indent
We say that we indent code. I'm writing a string builder which can add/remove tabs to indent code.

Sample:

```<code>builder.Add("<ul>");
builder.Indent();
builder.Add("<li></li>");
builder.Dedent(); // <-- what should this be named.
builder.Add("</ul>");
</code>```

What should I name the method?

答:
I know I'm a bit late to the party, but just had the same problem finding the opposite for Indent.
As here are several different answers to that question, I asked an English colleague (UK) what he would choose: His first tip was IncreaseIndent and DecreaseIndent. But Indent and Detent would also work.

Title: Opposite term of indent


答:
The indexOf method, used on an Array,  that quite all languages have, allows to compare a value to several others, so i guess a special operator doesn't make much sense.  </p>

<p>In javascript that would write :  </p>

```<code>if ( [b, c].indexOf(a) != -1 ) { ....  }
</code>```

Body:
The indexOf method, used on an Array,  that quite all languages have, allows to compare a value to several others, so i guess a special operator doesn't make much sense.

In javascript that would write :

if ( [b, c].indexOf(a) != -1 ) { ....  }


答:
So we could have like

```<code>ourUser.getOptionalAttributes()
// could return a list [Date Birthday, Float Height, Color Eyecolor]
// or just [Color Eyecolor]
// or even an empty list
</code>```

Am i totally on the wrong track here and are option types the (philosophical) correct way to express optional attributes?

The only time using a list would make sense is when a particular attribute may occur 0 to n > 1 times. I don't even know what you plan to do with the first example - that list is heterogeneous. (I'm not saying it's not possible - you could use case classes so that each list element holds either a Date, a Float, or a Color, but seriously, what does that get you?)

A Maybe/Option type is fundamentally the right thing to represent either Nothing or a single value of type T. If type T has n distinct values, Option <T> has n + 1 distinct values; and being a distinct type from T, it's an error to blindly assign an Option <T> to a T in the same way that it's wrong to blindly assign a 64-bit number to a 32-bit number.

For signaling failure in a computation, you could alternatively throw an exception instead of returning an Option. This is useful when a failure is likely to be handled higher up the call stack. It's also useful when passing functions to other functions. For example, you could have a function A that wants a function B that returns an integer. It may be the case that B could theoretically fail to produce an integer, but you've ensured that this particular use of B will produce a result. Having Option in the return type of B would make it incompatible with A.

Also, are there additional concepts for handling the logic of optional attributes other than nullable types and option-like types?

There's the concept of dividing values of your type into the appropriate case classes. As a simple example, suppose you're working with cartesian coordinates and need to work with both rectangular and polar coordinates. Although there's two representations, it's important to understand that they both represent values of the same type. A naive way of implementing this would be:

```<code>public class Point2D {
   public static enum Type { RECT, POLAR }
   public Type type;
   public Option<Double> x; // Rectangular coords
   public Option<Double> y; // Rectangular coords
   public Option<Double> angle; // Polar coords
   public Option<Double> magnitude; // Polar coords
}
</code>```

But this approach is wrong - it's not that every field (save for type) is optional, it's that there's two kinds of Point2Ds and you've conflated the two. If you modeled this correctly using case classes, none of the fields would be optional:

```<code>abstract class Point2D
case class Rect(x: double, y: double) extends Point2D
case class Polar(angle: double, magnitude: double) extends Point2D
</code>```

This is more related to choosing the right model than it is to "missing" values, but I mention it since it can lead to the wrong use of Option (or null, god forbid.)

As others have mentioned, there's the concept of the Null Object Pattern, but that's tied to the specific semantics of the type. A null object doesn't make sense for some types.

Body:
So we could have like

ourUser.getOptionalAttributes()
// could return a list [Date Birthday, Float Height, Color Eyecolor]
// or just [Color Eyecolor]
// or even an empty list

Am i totally on the wrong track here and are option types the (philosophical) correct way to express optional attributes?

The only time using a list would make sense is when a particular attribute may occur 0 to n > 1 times. I don't even know what you plan to do with the first example - that list is heterogeneous. (I'm not saying it's not possible - you could use case classes so that each list element holds either a Date, a Float, or a Color, but seriously, what does that get you?)

A Maybe/Option type is fundamentally the right thing to represent either Nothing or a single value of type T. If type T has n distinct values, Option <T> has n + 1 distinct values; and being a distinct type from T, it's an error to blindly assign an Option <T> to a T in the same way that it's wrong to blindly assign a 64-bit number to a 32-bit number.

For signaling failure in a computation, you could alternatively throw an exception instead of returning an Option. This is useful when a failure is likely to be handled higher up the call stack. It's also useful when passing functions to other functions. For example, you could have a function A that wants a function B that returns an integer. It may be the case that B could theoretically fail to produce an integer, but you've ensured that this particular use of B will produce a result. Having Option in the return type of B would make it incompatible with A.

Also, are there additional concepts for handling the logic of optional attributes other than nullable types and option-like types?

There's the concept of dividing values of your type into the appropriate case classes. As a simple example, suppose you're working with cartesian coordinates and need to work with both rectangular and polar coordinates. Although there's two representations, it's important to understand that they both represent values of the same type. A naive way of implementing this would be:

public class Point2D {
   public static enum Type { RECT, POLAR }
   public Type type;
   public Option<Double> x; // Rectangular coords
   public Option<Double> y; // Rectangular coords
   public Option<Double> angle; // Polar coords
   public Option<Double> magnitude; // Polar coords
}

But this approach is wrong - it's not that every field (save for type) is optional, it's that there's two kinds of Point2Ds and you've conflated the two. If you modeled this correctly using case classes, none of the fields would be optional:

abstract class Point2D
case class Rect(x: double, y: double) extends Point2D
case class Polar(angle: double, magnitude: double) extends Point2D

This is more related to choosing the right model than it is to "missing" values, but I mention it since it can lead to the wrong use of Option (or null, god forbid.)

As others have mentioned, there's the concept of the Null Object Pattern, but that's tied to the specific semantics of the type. A null object doesn't make sense for some types.


答:
The question is not whether it is "fair" or not but whether the test a) is eliminating candidates who do not have the skills needed for the job and b) letting through those candidates who do. As long as the test does this job well, you should continue asking it.

The details of the test depend on the needs you have and the standards you want to maintain. When I show to a candidate a piece of code where a database API call could raise an exception if the record is absent but the code that uses the API call is written to treat all exceptions raised by the call to mean "record is absent", I'd expect any candidate fit for any job I offer to point out that the code is swallowing exceptions. I don't have a position for someone who cannot see this problem.

One way to lessen the opportunity for uneasiness could be to just have an extremely simple coding test before having the "find the errors" test. Once candidates pass the initial documentary check (i.e. their résumé looks good), I find that most candidates that don't make it through are failing at the simple coding test stage.

Title: As an interviewer, asking a candidate to find errors in small sample code. Is this fair?

Body:
We've been interviewing on and off for about two years, and I've run this by about 30 candidates. I wrote some 20 lines of code which perform a relatively basic operation, but has a bunch of errors in it. None of them are syntax errors. Errors range from bad memory management, incorrect data types, multithreading problems, misuse of keywords, and a couple functional errors that would give undesired output.

People get really nervous during this question. Is it a fair question to be asking? The goal is to get an idea of their comfort level with the language (Objective C has some very strange behaviors, and most applicants we get are relatively inexperienced in ObjC specifically as compared to other languages), as well as see their ability to recognize logical problems in otherwise foreign code.

Once a candidate has made a first pass, I often will point to specific lines that have remaining errors on them and see how much hand-holding it takes to get a correct identification and/or fix from them.

At our company, this is a real world scenario, as programmers would be thrust straight into a 100k line app and given bugs to fix, and we need people that are comfortable with working with the code of 6 other programmers.

However, today, another of our interviewers told me he hated this problem (I didn't quite understand what his reason was, admittedly). Is this something I should continue asking, or should I look for alternate avenues?


问:
If null is bad, why do modern languages implement it?
I'm sure designers of languages like Java or C# knew issues related to existence of null references (see Are null references really a bad thing?). Also implementing an option type isn't really much more complex than null references.

Why did they decide to include it anyway? I'm sure lack of null references would encourage (or even force) better quality code (especially better library design) both from language creators and users.

Is it simply because of conservatism - "other languages have it, we have to have it too..."?

答:
I wouldn't go so far as "other languages have it, we have to have it too..." like it's some sort of keeping up with the Joneses. A key feature of any new language is the ability to interoperate with existing libraries in other languages (read: C). Since C has null pointers, the interoperability layer necessarily needs the concept of null (or some other "does not exist" equivalent that blows up when you use it).

The language designer could've chosen to use Option Types and force you to handle the null path everywhere that things could be null. And that almost certainly would lead to less bugs.

But (especially for Java and C# due to the timing of their introduction and their target audience) using option types for this interoperability layer would likely have harmed if not torpedoed their adoption. Either the option type is passed all the way up, annoying the hell out of C++ programmers of the mid to late 90's - or the interoperability layer would throw exceptions when encountering nulls, annoying the hell out of C++ programmers of the mid to late 90's...


答:
Disclaimer: Since I don't know any language designers personally, any answer I give you will be speculative.

From Tony Hoare himself:

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

Emphasis mine.

Naturally it didn't seem like a bad idea to him at the time. It's likely that it's been perpetuated in part for that same reason - if it seemed like a good idea to the Turing Award-winning inventor of quicksort, it's not surprising that many people still don't understand why it's evil. It's also likely in part because it's convenient for new languages to be similar to older languages, both for marketing and learning curve reasons. Case in point:

"We were after the C++ programmers. We managed to drag a lot of them about halfway to Lisp."
  -Guy Steele, co-author of the Java spec

(Source: http://www.paulgraham.com/icad.html)

And, of course, C++ has null because C has null, and there's no need to go into C's historical impact. C# kind of superseded J++, which was Microsoft's implementation of Java, and it's also superseded C++ as the language of choice for Windows development, so it could've gotten it from either one.

EDIT Here's another quote from Hoare worth considering:

Programming languages on the whole are very much more complicated than they used to be: object orientation, inheritance, and other features are still not really being thought through from the point of view of a coherent and scientifically well-based discipline or a theory of correctness. My original postulate, which I have been pursuing as a scientist all my life, is that one uses the criteria of correctness as a means of converging on a decent programming language design—one which doesn’t set traps for its users, and ones in which the different components of the program correspond clearly to different components of its specification, so you can reason compositionally about it. [...] The tools, including the compiler, have to be based on some theory of what it means to write a correct program.
  -Oral history interview by Philip L. Frana, 17 July 2002, Cambridge, England; Charles Babbage Institute, University of Minnesota.[ http://www.cbi.umn.edu/oh/display.phtml?id=343]

Again, emphasis mine. Sun/Oracle and Microsoft are companies, and the bottom line of any company is money. The benefits to them of having null may have outweighed the cons, or they may have simply had too tight a deadline to fully consider the issue. As an example of a different language blunder that probably occurred because of deadlines:

It's a shame that Cloneable is broken, but it happens. The original Java APIs were done very quickly under a tight deadline to meet a closing market window. The original Java team did an incredible job, but not all of the APIs are perfect. Cloneable is a weak spot, and I think people should be aware of its limitations. -Josh Bloch

(Source: http://www.artima.com/intv/bloch13.html)

Title: If null is bad, why do modern languages implement it?

Body:
I'm sure designers of languages like Java or C# knew issues related to existence of null references (see Are null references really a bad thing?). Also implementing an option type isn't really much more complex than null references.

Why did they decide to include it anyway? I'm sure lack of null references would encourage (or even force) better quality code (especially better library design) both from language creators and users.

Is it simply because of conservatism - "other languages have it, we have to have it too..."?


问:
When adding 7, 3, and 1 into a red-black tree, do I need to perform a right rotation?
If I add the following in this order into a red-black tree:

```<code>tree.Put(7)
tree.Put(3)
tree.Put(1)

         7                  3
        /   rotate(3)      / \
       3    ----->        1   7
      /
     1
</code>```

should I perform a right rotation after the insertion of 1 ?

I am reading the algorithms bible but it the pseudocode doesn't indicate what to do.

答:
At the root, 7 is black. After inserting the 3, it is red (because all inserted nodes are reds).

When you insert the 1, it is also red, so you have violated one property (the son of a red node must be black). Since you also need to maintain the fact that all paths have the same number of black nodes, you cannot simply color the 3 in black.

So you need to perform a rotation.

After checking the book: I believe this is case 3: color the grandparent red & perform right rotation.


问:
Lexing: One token per operator, or one universal operator token?
When lexing, what would be the best way to tokenize operators? Would one just create a BinaryOperator token, or a separate token for every single binary operator? Examples: PlusOperator, MinusOperator, DivisionOperator ...

I am tended towards having a universal one, but going from the documentations and project sources I've read the vast majority of lexers are using one token per operator. Is there a particular reason for this? Does it even matter? Does it give you any advantages?

答:
Most parser generators require different operators to be distinguished at the lexical analysis stage. If you're writing the parser by hand, then either option is fine.

If you use a universal 'operator' token type, you will (probably) be able to write a general expression parser with your operators (including precedence information) defined in a data structure (rather than hard-wired into the parser code), which might be nicer if you have a lot of operators, and would be essential if you're parsing a language which allows user defined operators.

Using a separate token type for each operator lets you maintain a clearer distinction between the (traditional) lexical and syntactic analysis stages, and may make it easier for other people (who are familiar with having separate lexers and parser) to understand your system.

Overall, I think this is just a stylistic choice in most cases.


答:
Since the tokens signify something literally different, make them unique.  If you need to understand the set of them as a single item, the place to do that is in the parser grammar:

```<code>operator := PlusOperator | MinusOperator | DivisionOperator
</code>```

Remember that the lexer's job is to split the input and not make any semantic decisions about its meaning.  That's the parser's business, and I'd opt not to put any kind of meaning into the names of the tokens:

```<code>operator := PLUS | MINUS | DIVIDE
</code>```

Title: Lexing: One token per operator, or one universal operator token?

Body:
When lexing, what would be the best way to tokenize operators? Would one just create a BinaryOperator token, or a separate token for every single binary operator? Examples: PlusOperator, MinusOperator, DivisionOperator ...

I am tended towards having a universal one, but going from the documentations and project sources I've read the vast majority of lexers are using one token per operator. Is there a particular reason for this? Does it even matter? Does it give you any advantages?

Body:
Since the tokens signify something literally different, make them unique.  If you need to understand the set of them as a single item, the place to do that is in the parser grammar:

operator := PlusOperator | MinusOperator | DivisionOperator

Remember that the lexer's job is to split the input and not make any semantic decisions about its meaning.  That's the parser's business, and I'd opt not to put any kind of meaning into the names of the tokens:

operator := PLUS | MINUS | DIVIDE


答:
I once wrote a program that used one universal operator type. It was a horrible idea, because the number of checks exploded. To check whether I had an addition operator, I would have to check that the current token is an operator token and contains the "+" string as value.

When using different tokens for different operators, you enjoy a number of benefits:

If you use a parser generator, then using a different token type for each operator makes handling operators much easier. Depending on the generator, it may actually be impossible to deal with operator precedence unless each operator has a different token type.

Specifically, a context-free parser is limited to only considering the type of each token. Otherwise, we quickly land in “recursively enumerable” territory.

You don't have to store the lexed string of an operator, as all necessary information is already stored in the token type.


问:
Algorithm to create permutations for a given alphabet based on a sequence number
I would like to have a function that will create a word (always the same word) for a given sequence number based on a given alphabet.

```<code>word(0, [a,b,c]) = a
word(1, [a,b,c]) = b
word(2, [a,b,c]) = c
word(3, [a,b,c]) = aa
word(4, [a,b,c]) = ab
word(5, [a,b,c]) = ac
word(6, [a,b,c]) = ba
word(7, [a,b,c]) = bb
word(8, [a,b,c]) = bc
word(9, [a,b,c]) = ca
...
</code>```

I was able to recursively create all permutations of a given length but starting with length 5 it already gets quite big in memory.

答:
Let  n be the size of alphabet (here 3).

Now ath number in the above scheme will lie between

0 <= a < n
or
0 + n <= a < 0 + n + n*n
or
...

0 + n + n^2 + ... + n^m <= a < 0 + n + n^2 + ... + n^(m+1)

Solving for m we get,

m = int(log(a(n-1)/n + 1)/log(n))

Here it is,

m = int(log(2*a/3 + 1)/log(3))

Now we subtract n*(n^m-1)/(n-1) from a getting b. b will be a number of (m+1) places in a number system with radix n.

I have put a small python code for it like this:

```<code>from math import*

f = lambda a : int(log(2*a/3.0 + 1.0)/ log(3))

alpha = ['a','b','c']

def get_repr(a):
    m = f(a)
    if m == 0:
        b = a
    else:
        trunc = 3*((3**m)-1)/(2)
        b = a - trunc
    s = ''
    for q in range(0, m+1):
        s =   alpha[(b%3)] + s
        b /= 3
    return s

print get_repr(8)
</code>```

EDIT: We can avoid jargon of logarithm and all, and can use the following:

```<code>def word(a, alphabet):
    k = 1
    N = len(alphabet)
    n = N
    while True:
        if a < n:
            break
        else:
            a = a - n
            n = n*N
            k = k + 1
    s = ''
    for q in range(0, k):
        s =   alphabet[(a%N)] + s
        a /= N
    return s

print word(1, ['a','b','c'])
</code>```

Body:
Let  n be the size of alphabet (here 3).

Now ath number in the above scheme will lie between

0 <= a < n
or
0 + n <= a < 0 + n + n*n
or
...

0 + n + n^2 + ... + n^m <= a < 0 + n + n^2 + ... + n^(m+1)

Solving for m we get,

m = int(log(a(n-1)/n + 1)/log(n))

Here it is,

m = int(log(2*a/3 + 1)/log(3))

Now we subtract n*(n^m-1)/(n-1) from a getting b. b will be a number of (m+1) places in a number system with radix n.

I have put a small python code for it like this:

from math import*

f = lambda a : int(log(2*a/3.0 + 1.0)/ log(3))

alpha = ['a','b','c']

def get_repr(a):
    m = f(a)
    if m == 0:
        b = a
    else:
        trunc = 3*((3**m)-1)/(2)
        b = a - trunc
    s = ''
    for q in range(0, m+1):
        s =   alpha[(b%3)] + s
        b /= 3
    return s

print get_repr(8)

EDIT: We can avoid jargon of logarithm and all, and can use the following:

def word(a, alphabet):
    k = 1
    N = len(alphabet)
    n = N
    while True:
        if a < n:
            break
        else:
            a = a - n
            n = n*N
            k = k + 1
    s = ''
    for q in range(0, k):
        s =   alphabet[(a%N)] + s
        a /= N
    return s

print word(1, ['a','b','c'])


问:
Is there a viable alternative to the agile development methodology?
The two predominant software-development methodologies are waterfall and agile.  When discussing these two, there is often much focus on the particular practices that distinguish them (pair programming, TDD, etc. vs. functional spec, big up-front design, etc.)

But the real differences are far deeper, in that these practices come from a philosophy.

Waterfall says:  Change is costly, so it should be minimized.

Agile says:  Change is inevitable, so make change cheap.

My question is, regardless of what you think of TDD or functional specs, is the waterfall development methodology really viable?

Does anyone really think that minimizing change in software is a viable option for those that desire to deliver valuable software?  Or is the question really about what sort of practices work best in our situations to manage the inevitable change?

答:
Yes, Waterfall, Spiral, Iterative and other hybrid process models are all viable, but change is inevitable.  Process is more than just about how to handle change, and (I claim that) the biggest determinant is how well you know/understand the problem, and how accurately you can plan and predict.

Stating that "the two predominant software-development methodologies are waterfall and agile" is disingenous, as there is a spectrum of software development processes, and many companies synthesize their own version of the process model, often changing for a given project.  There are more than two viable approaches to software development.  Although Waterfall and Agile tend to fall on opposite ends of the "change" spectrum, it is reasonable to typify these competing methodologies as,

Waterfall says: Change is costly, so it should be minimized.

Agile says: Change is inevitable, so make change cheap.

But that is not the whole story.  Business needs to be able to plan and predict, but software is a creative process, and estimates are often wrong. Remember the good - fast - cheap triangle?  Add a fourth dimension, process, and you find that reducing process effort can also compress the schedule, when the estimates turn out to be wrong and a project is in danger of delay. Software is a fungible (mutable) process, and Agile, Iterative, Spiral all offer the ability to deliver incremental functionality in shorter intervals.

Waterfall and other requirements driven process models have controls for handling change, so it is inaccurate to say Waterfall minimizes change, it is more accurate to say Waterfall recognizes and manages change, and communicates the impact of that change (because change causes schedule impact when you have requirements and design up front).  When you are building a product, or have need to fully-define requirements (functionality), you are driven to one of the hybrid models.

And when estimates are wrong, often process (the fourth leg of the iron triangle) is sacrificed to meet the schedule.


问:
Why don't languages include implication as a logical operator?
It might be a strange question, but why there is no implication as a logical operator in many languages (Java, C, C++, Python Haskell - although as last one have user defined operators its trivial to add it)? I find logical implication much clearer to write (particularly in asserts or assert-like expressions) then negation with or:</p>

```<code>encrypt(buf, key, mode, iv = null) {
    assert (mode != ECB --> iv != null);
    assert (mode == ECB || iv != null);
    assert (implies(mode != ECB, iv != null)); // User-defined function
}
</code>```

答: Racket has implies. It macro-expands to an if expression.


问:
Using subclasses for DataContracts used with JSON
I have a RESTful call that can modify the state of an instance. My problem is that the JSON  is different based on the type of action the user is taking, it could be a SetProperty action or a SetState action (among others).

For example, a POST /api/sample/ _would send the following JSON

```<code>{
  instanceId: 12312,
  actionId: 12345, // Maps to a SetState action
  desiredState: 'CURATION'
}
</code>```

But when calling the same URL for a SetProperty, the JSON would look like

```<code>{
  instanceId: 12312,
  actionId: 25354, // Maps to a SetProperty action
  propName: "PropA",
  propValue: "user-input"
}
</code>```

I use the following data contract

```<code>[DataContract]
class PostInstanceRequest {
    [DataMember]
    int instanceId;
    [DataMember]
    int actionId;
    [DataMember]
    string desiredState;  // Only used for SetState
    [DataMember]
    string propName;   // Only used for SetProperty
    [DataMember]
    string propValue;  // Only used for SetProperty
    // Many more action specific properties here...
}
</code>```

I don't really like this because it feels like I should have a base class for the common properties, and then I should define more base classes with the specific properties.

SetStatePostInstanceRequest, that adds desiredState

SetPropertyPostInstanceRequest, that adds propName and propValue

However, if I do that, I don't know what class to deserialize it into. I would have to first deserialize as a PostInstanceRequest, check the actionId property, and then deserialize it to the correct subclass.

A possible compromise is to use composition

```<code>[DataContract]
class SetStateAction {
    [DataMember]
    string desiredState;
}

[DataContract]
class SetPropAction {
    [DataMember]
    string propName;
    [DataMember]
    string propValue;
}

[DataContract]
class PostInstanceRequest {
    [DataMember]
    int instanceId;
    [DataMember]
    int actionId;
    [DataMember]
    SetPropAction setPropParams;
    [DataMember]
    SetStateAction setActionParams;
    // More references to action specific classes down here
}
</code>```

Which of the options is going to cause me less trouble? Or is there an even better way that I didn't think of?

答:
Did you author the service which you are posting to? If so, I would recommend changing it, so that you post SetState data to something like /api/sample/State, and post SetProperty data to /api/sample/Property. Then you would have separate controller actions for each service method, with each receiving only the desired parameters. If the service isn't yours and you can't modify it however, then obviously you're a bit stuffed. Otherwise, read this: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

Update

If you definitely want to retain a single action, at the same address, there is something you can do. You can define your controller action to take an interface / base class-typed parameter, and have the json deserializer use type information which you provide in your json to determine which class to rehydrate with your data, for example:

public abstract class ThingBase
{
    public int instanceId { get ; set; }
    public int actionId { get; set; }
}

public class SetStateThing : ThingBase
{
    public string desiredState { get; set; }
}

public class SetPropertyThing : ThingBase
{
    public string propName { get; set; }
    public string propValue { get; set; }
}

public class MyController
{
    public HttpResponseMessage Post([FromBody]ThingBase thing)
    {
        //use thing
    }
}
```

<p>Your json would become, for example:
</p>

```{
$type: "MyAssembly.SetStateThing, MyAssembly",
instanceId: 12312,
actionId: 12345, // Maps to a SetState action
desiredState: "CURATION"
}

{
$type: "MyAssembly.SetPropertyThing, MyAssembly",
instanceId: 12312,
actionId: 25354, // Maps to a SetProperty action
propName: "PropA",
propValue: "user-input"
}
```

The trick is to set up the serializer settings correctly (in your WebApiConfig.cs Register(HttpConfiguration config) method for example):

config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;

I used this with an interface, but an abstract base class seems a better fit for your scenario.

OwnerDisplayName: Juan Mendes

Body:
Did you author the service which you are posting to? If so, I would recommend changing it, so that you post SetState data to something like /api/sample/State, and post SetProperty data to /api/sample/Property. Then you would have separate controller actions for each service method, with each receiving only the desired parameters. If the service isn't yours and you can't modify it however, then obviously you're a bit stuffed. Otherwise, read this: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

Update

If you definitely want to retain a single action, at the same address, there is something you can do. You can define your controller action to take an interface / base class-typed parameter, and have the json deserializer use type information which you provide in your json to determine which class to rehydrate with your data, for example:

public abstract class ThingBase
{
    public int instanceId { get ; set; }
    public int actionId { get; set; }
}

public class SetStateThing : ThingBase
{
    public string desiredState { get; set; }
}

public class SetPropertyThing : ThingBase
{
    public string propName { get; set; }
    public string propValue { get; set; }
}

public class MyController
{
    public HttpResponseMessage Post([FromBody]ThingBase thing)
    {
        //use thing
    }
}

Your json would become, for example:

{
$type: "MyAssembly.SetStateThing, MyAssembly",
instanceId: 12312,
actionId: 12345, // Maps to a SetState action
desiredState: "CURATION"
}

{
$type: "MyAssembly.SetPropertyThing, MyAssembly",
instanceId: 12312,
actionId: 25354, // Maps to a SetProperty action
propName: "PropA",
propValue: "user-input"
}

The trick is to set up the serializer settings correctly (in your WebApiConfig.cs Register(HttpConfiguration config) method for example):

config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;

I used this with an interface, but an abstract base class seems a better fit for your scenario.


问:
null pointers vs. Null Object Pattern
Attribution: This grew out of a related P.SE question

My background is in C / C++, but I have worked a fair amount in Java and am currently coding C#.  Because of my C background, checking passed and returned pointers is second-hand, but I acknowledge it biases my point of view.

I recently saw mention of the Null Object Pattern where the idea is that an object is always returned.  Normal case returns the expected, populated object and the error case returns empty object instead of a null pointer.  The premise being that the calling function will always have some sort of object to access and therefore avoid null access memory violations.

So what are the pros / cons of a null check versus using the Null Object Pattern?

I can see cleaner calling code with the NOP, but I can also see where it would create hidden failures that don't otherwise get raised.  I would rather have my application fail hard (aka an exception) while I'm developing it than have a silent mistake escape into the wild.

Can't the Null Object Pattern have similar problems as not performing a null check?

Many of the objects I have worked with hold objects or containers of their own.  It seems like I would have to have a special case to guarantee all of the main object's containers had empty objects of their own.  Seems like this could get ugly with multiple layers of nesting.

答:
For some additional viewpoint, have a look at Objective-C, where instead of having a Null object the value nil kind-of works like an object. Any message sent to a nil object has no effect and returns a value of 0 / 0.0 / NO (false) / NULL / nil, whatever the return value type of the method is. This is used as a very pervasive pattern in MacOS X and iOS programming, and usually methods will be designed so that a nil object returning 0 is a reasonable result.

For example, if you want to check whether a string has one or more characters, you could write

```<code>aString.length > 0
</code>```

and get a reasonable result if aString == nil, because a non-existing string doesn't contain any characters. People tend to take a while to get used to it, but it would probably take me a while to get used to checking for nil values everywhere in other languages.

(There's also a singleton object of class NSNull which behaves quite different and isn't used very much in practice).

Title: null pointers vs. Null Object Pattern

Body:
For some additional viewpoint, have a look at Objective-C, where instead of having a Null object the value nil kind-of works like an object. Any message sent to a nil object has no effect and returns a value of 0 / 0.0 / NO (false) / NULL / nil, whatever the return value type of the method is. This is used as a very pervasive pattern in MacOS X and iOS programming, and usually methods will be designed so that a nil object returning 0 is a reasonable result.

For example, if you want to check whether a string has one or more characters, you could write

aString.length > 0

and get a reasonable result if aString == nil, because a non-existing string doesn't contain any characters. People tend to take a while to get used to it, but it would probably take me a while to get used to checking for nil values everywhere in other languages.

(There's also a singleton object of class NSNull which behaves quite different and isn't used very much in practice).


问:
Logging events for reporting purposes
Are there any design patterns or best practices around logging events for use in reporting and BI systems.

For example in a system which manages orders from a website, it would be beneficial if a customer support worker could type in an order number and see that it the order was placed  on a certain day, dispatched on a certain day and delivered on another.

I can see 2 ways around this. I have an order object which has the fields:

```<code>OrderDate
DespatchDate
DeliveryDate
</code>```

and populate them if they have happend otherwise they will be null

OR

log some sort of events like which are messages like:

```<code>Order Number - "12312312" - Ordered on '2014/01/01'
Order Number - "12312312" - Despatched on '2014/01/01'
</code>```

and add store the events in a database.

Are there any guidelines for this?
For example how does the work item history in TFS work?

答:
If this is an actual business-related report that is going to be generated and given to someone, then generate event records into a database, and then create a report from those records.  Give the records actual semantic meaning, rather than merely attaching a message.  In other words, make them first-class citizens.

Logging serves a different purpose.  Logging is intended as a systems monitoring tool, not a business logic mechanism.  If the report is an integral part of running the business, then make it an integral part of the application.

Title: Logging events for reporting purposes


答:
Because programming languages are generally designed to be practically useful rather than technically correct. The fact is that null states are a common occurrence due to either bad or missing data or a state that has not yet been decided. The technically superior solutions are all more unwieldy than simply allowing null states and sucking up the fact that programmers make mistakes.

For example, if I want to write a simple script that works with a file, I can write pseudocode like:

```<code>file = openfile("joebloggs.txt")

for line in file
{
  print(line)
}
</code>```

and it will simply fail if joebloggs.txt doesn't exist. The thing is, for simple scripts that's probably okay and for many situations in more complex code I know it exists and the failure won't happen so forcing me to check wastes my time. The safer alternatives achieve their safety by forcing me to deal correctly with the potential failure state but often I don't want to do that, I just want to get on.

Body:
Because programming languages are generally designed to be practically useful rather than technically correct. The fact is that null states are a common occurrence due to either bad or missing data or a state that has not yet been decided. The technically superior solutions are all more unwieldy than simply allowing null states and sucking up the fact that programmers make mistakes.

For example, if I want to write a simple script that works with a file, I can write pseudocode like:

file = openfile("joebloggs.txt")

for line in file
{
  print(line)
}

and it will simply fail if joebloggs.txt doesn't exist. The thing is, for simple scripts that's probably okay and for many situations in more complex code I know it exists and the failure won't happen so forcing me to check wastes my time. The safer alternatives achieve their safety by forcing me to deal correctly with the potential failure state but often I don't want to do that, I just want to get on.