答:
It seems like you are getting too detailed too fast.  You should break it down more.  You should observe the code for its code quality and for its feature compliance.  You should have both separated out and that isn't even the end of the story... so here's my suggestion:

Code quality:

Automated checks:

Conformation of style: is the naming
convention correct, are all code
properly indented, etc.

Efficiency
standard: check for memory leaks,
complexity check, redundant
variables, etc.

Actual Peer Review:

A simple walk through of the design

explanation of deviations from the automated checks

Ease of maintenance, talk about how you can maintain it and all

Testability: how easy is it to test this code? Got a plan?

Feature compliance:

A review of the feature requirements and any changes since the requirements and/or design review

Demo the functionality associated with the requirements and check them off one by one

Discuss any additional requirements in the other aspects of the software encountered during implementation (like deployment plans, infrastructure, etc.)

Explanation of any deviations from requirements, if any by that point.

If you can cover yourself on these two aspects of a code review, you're golden.

OwnerDisplayName: jghost


问:
Is a code review subjective or objective (quantifiable)?
I am putting together some guidelines for code reviews. We do not have one formal process yet and are trying to formalize it. And our team is geographically distributed.

We are using TFS for source control (we used it for tasks/bug tracking/project management as well, but we migrated that to JIRA) with Visual Studio 2008 for development.

What are the things you look for when doing a code review?

These are the things I came up with

Enforce FxCop rules (we are a Microsoft shop)

Check for performance (any tools ?) and security (thinking about using
OWASP - code crawler) and thread safety

Adhere to naming conventions

The code should cover edge cases and boundaries conditions

Should handle exceptions correctly (do not swallow exceptions)

Check if the functionality is duplicated elsewhere

A method body should be small (20-30 lines), and methods should do one
thing and one thing only (no side
effects and avoid temporal coupling -)

Do not pass/return nulls in methods

Avoid dead code

Document public and protected methods/properties/variables

What other things should we generally look out for?

I am trying to see if we can quantify the review process (it would produce identical output when reviewed by different persons) Example: Saying "the method body should be no longer than 20-30 lines of code" as opposed to saying "the method body should be small".

Or is code review very subjective (and would differ from one reviewer to another)?

The objective is to have a marking system (say -1 point for each FxCop rule violation, -2 points for not following naming conventions, 2 points for refactoring, etc.) so that developers would be more careful when they check in their code. This way, we can identify developers who are consistently writing good/bad code. The goal is to have the reviewer spend about 30 minutes max, to do a review (I know this is subjective, considering the fact that the changeset/revision might include multiple files/huge changes to the existing architecture, etc., but you get the general idea, the reviewer should not spend days reviewing someone's code).

What other objective/quantifiable system do you follow to identify good/bad code written by developers?

Book reference: Clean Code: A handbook of agile software craftmanship by Robert Martin.

答:
My experiences with code review is that it should be a combined effort to improve code, not a 'measure' to decide who is good or bad at their job. When it doesn't matter if you get a lot of remarks during your code review, reviewers will be more strict, hence giving suggestions to improve the code.

To improve the quality of checked in code enforce that review comments are processed (let the reviewer approve the processed comments) and also use static code checking tools to force a level of quality for the initial commit.

OwnerDisplayName: ram

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Thirler


答:
A marking system sounds tricky to get right, but worthwhile to have as a measurement tool: you cannot improve what you cannot measure.  But you should probably accept that some things will be difficult/impossible to quantify accurately.  The tricky thing will be working out how many points each quality should score: for example, if adhering to naming conventions scores 2 points, then how many points for keeping methods small?

Maybe something like a simple checklist would be better, so that code can be marked as conforming, partially conforming or not conforming to a particular quality.  Later, you can add scoring to the checklist once you see what quality issues come up the most often, or cause the most problems.

The review process should also be flexible enough to allow code to fail parts of the review, provided that this can be justified and documented.  Blindly sticking to some code quality standard which causes a component to become unnecessarily complex/unmanageable is a bad idea!

Title: Is a code review subjective or objective (quantifiable)?

Body:
I am putting together some guidelines for code reviews. We do not have one formal process yet and are trying to formalize it. And our team is geographically distributed.

We are using TFS for source control (we used it for tasks/bug tracking/project management as well, but we migrated that to JIRA) with Visual Studio 2008 for development.

What are the things you look for when doing a code review?

These are the things I came up with

Enforce FxCop rules (we are a Microsoft shop)

Check for performance (any tools ?) and security (thinking about using
OWASP - code crawler) and thread safety

Adhere to naming conventions

The code should cover edge cases and boundaries conditions

Should handle exceptions correctly (do not swallow exceptions)

Check if the functionality is duplicated elsewhere

A method body should be small (20-30 lines), and methods should do one
thing and one thing only (no side
effects and avoid temporal coupling -)

Do not pass/return nulls in methods

Avoid dead code

Document public and protected methods/properties/variables

What other things should we generally look out for?

I am trying to see if we can quantify the review process (it would produce identical output when reviewed by different persons) Example: Saying "the method body should be no longer than 20-30 lines of code" as opposed to saying "the method body should be small".

Or is code review very subjective (and would differ from one reviewer to another)?

The objective is to have a marking system (say -1 point for each FxCop rule violation, -2 points for not following naming conventions, 2 points for refactoring, etc.) so that developers would be more careful when they check in their code. This way, we can identify developers who are consistently writing good/bad code. The goal is to have the reviewer spend about 30 minutes max, to do a review (I know this is subjective, considering the fact that the changeset/revision might include multiple files/huge changes to the existing architecture, etc., but you get the general idea, the reviewer should not spend days reviewing someone's code).

What other objective/quantifiable system do you follow to identify good/bad code written by developers?

Book reference: Clean Code: A handbook of agile software craftmanship by Robert Martin.

OwnerDisplayName: KarstenF

ContentLicense: CC BY-SA 2.5


答:
My only advice would be to avoid making your code review process too strict - the most important thing is that the code review actually happens and that it is taken seriously.

The more exhausting the process is for the reviewer the less likely it is that code reviews will happen and that they will be taken seriously rather than just seen as an annoyance. Besides, the real value of code reviews lies in the ability of the reviewer to use their own judgement automated tools can be used to check for things like whether FXCop rules pass.

OwnerDisplayName: Kragen


答:
Grading individuals in a review is counter to most successful systems I've worked with, maybe all. But the goal I've been trying to reach for more than 20 years is fewer bugs and increased productivity per-engineer-hour. If grading individuals is a goal, I suppose reviews could be used. I've never seen a situation where it was required, as a worker or as a leader.

Some objective study (Fagan, etc.) and a lot of popular wisdom suggests that peer relationships facilitate code reviews aimed at reducing bugs and increasing productivity. Working managers may participate as workers, but not as managers. Points of discussion are noted, changes to satisfy reviewers are generally a good thing but not required. Hence the peer relationship.

Any automated tools that can be accepted without further analysis or judgment are good - lint in C, C++, Java. Regular compilation. Compilers are REALLY good at findng compiler bugs. Documenting deviations in automated checks sounds like a subtle indictment of the automated checks. Code directives (like Java does) that allow deviations are pretty dangerous, IMHO. Great for debugging, to allow you to get the heart of the matter, quickly. Not so good to find in a poorly documented, 50,000 non-comment-line block of code you've become responsible for.

Some rules are stupid but easy to enforce; defaults for every switch statement even when they're unreachable, for example. Then it's just a check box, and you don't have to spend time and money testing with values which don't match anything. If you have rules, you'll have foolishness, they are inextricably linked. Any rule's benefit should be worth the foolishness it costs, and that relationship should be checked at regular intervals.

On the other hand, "It runs" is no virtue before review, or defense in review. If development followed the waterfall model, you'd like to do the review when coding is 85% complete, before complicated errors were found and worked out, because review is a cheaper way to find them. Since real life isn't the waterfall model, when to review is somewhat of an art and amounts to a social norm. People who will actually read your code and look for problems in it are solid gold. Management that supports this in an on-going way is a pearl above price. Reviews should be like checkins- early and often.

I've found these things beneficial:

1) No style wars. Where open curly braces go should only be subject to a consistency check in a given file. All the same. That's fine then. Ditto indentation depth**s and **tab widths. Most organizations discover they need a common standard for tab, which is used as a large space.

2)  `Ragged

```<code>   looking
</code>```

text
that doesn't

```<code>   line up is hard to read
</code>```

for content.`

BTW, K&R indented five (FIVE) spaces, so appeals to authority are worthless. Just be consistent.

3) A line-numbered, unchanging, publicly available copy of the file to be reviewed should be pointed to for 72 hours or more before the review.

4) No design-on-the-fly. If there's a problem, or an issue, note its location, and keep moving.

5) Testing that goes through all paths in the development environment is a very, very, very, good idea. Testing that requires massive external data, hardware resources, use of the customer's site, etc, etc. is testing that costs a fortune and won't be thorough.

6) A non-ASCII file format is acceptable if creation, display, edit, etc., tools exist or are created early in development. This is a personal bias of mine, but in a world where the dominant OS can't get out of its own way with less than 1 gigabyte of RAM, I can't understand why files less than, say, 10 megabytes should be anything other than ASCII or some other commercially supported format. There are standards for graphics, sound, movies, executable, and tools that go with them. There is no excuse for a file containing a binary representation of some number of objects.

For maintenance, refactoring or development of released code, one group of co-workers I had used review by one other person, sitting at a display and looking at a diff of old and new, as a gateway to branch check-in. I liked it, it was cheap, fast, relatively easy to do. Walk-throughs for people who haven't read the code in advance can be educational for all but seldom improve the developer's code.

If you're geographically distributed, looking at diffs on a screen while talking with someone else looking at the same would be relatively easy. That covers two people looking at changes. For a larger group who have read the code in question, multiple sites isn't a lot harder than all in one room. Multiple rooms linked by shared computer screens and squak boxes work very well, IMHO. The more sites, the more meeting management is needed. A manager as facilitator can earn their keep here. Remember to keep polling the sites you're not at.

At one point, the same organization had automated unit testing which was used as regression testing. That was really nice. Of course we then changed platforms and automated test got left behind. Review is better, as the Agile Manifesto notes, relationships are more important than process or tools. But once you've got review, automated unit tests/regression tests are the next most important help in creating good software.

If you can base the tests on requirements, well, like the lady says in "When Harry Met Sally", I'll have what she's having!

All reviews need to have a parking lot to capture requirements and design issues at the level above coding. Once something is recognized as belonging in the parking lot, discussion should stop in the review.

Sometimes I think code review should be like schematic reviews in hardware design- completely public, thorough, tutorial, the end of a process, a gateway after which it gets built and tested. But schematic reviews are heavyweight because changing physical objects is expensive. Architecture, interface and documentation reviews for software should probably be heavyweight. Code is more fluid. Code review should be lighter weight.

In a lot of ways, I think technology is as much about culture and expectation as it is about a specific tool. Think of all the "Swiss Family Robinson"/Flintstones/McGyver improvisations that delight the heart and challenge the mind. We want our stuff to work. There isn't a single path to that, any more than there was "intelligence" which could somehow be abstracted and automated by 1960s AI programs.

Body:
Grading individuals in a review is counter to most successful systems I've worked with, maybe all. But the goal I've been trying to reach for more than 20 years is fewer bugs and increased productivity per-engineer-hour. If grading individuals is a goal, I suppose reviews could be used. I've never seen a situation where it was required, as a worker or as a leader.

Some objective study (Fagan, etc.) and a lot of popular wisdom suggests that peer relationships facilitate code reviews aimed at reducing bugs and increasing productivity. Working managers may participate as workers, but not as managers. Points of discussion are noted, changes to satisfy reviewers are generally a good thing but not required. Hence the peer relationship.

Any automated tools that can be accepted without further analysis or judgment are good - lint in C, C++, Java. Regular compilation. Compilers are REALLY good at findng compiler bugs. Documenting deviations in automated checks sounds like a subtle indictment of the automated checks. Code directives (like Java does) that allow deviations are pretty dangerous, IMHO. Great for debugging, to allow you to get the heart of the matter, quickly. Not so good to find in a poorly documented, 50,000 non-comment-line block of code you've become responsible for.

Some rules are stupid but easy to enforce; defaults for every switch statement even when they're unreachable, for example. Then it's just a check box, and you don't have to spend time and money testing with values which don't match anything. If you have rules, you'll have foolishness, they are inextricably linked. Any rule's benefit should be worth the foolishness it costs, and that relationship should be checked at regular intervals.

On the other hand, "It runs" is no virtue before review, or defense in review. If development followed the waterfall model, you'd like to do the review when coding is 85% complete, before complicated errors were found and worked out, because review is a cheaper way to find them. Since real life isn't the waterfall model, when to review is somewhat of an art and amounts to a social norm. People who will actually read your code and look for problems in it are solid gold. Management that supports this in an on-going way is a pearl above price. Reviews should be like checkins- early and often.

I've found these things beneficial:

1) No style wars. Where open curly braces go should only be subject to a consistency check in a given file. All the same. That's fine then. Ditto indentation depth**s and **tab widths. Most organizations discover they need a common standard for tab, which is used as a large space.

2)  `Ragged

   looking

text
that doesn't

   line up is hard to read

for content.`

BTW, K&R indented five (FIVE) spaces, so appeals to authority are worthless. Just be consistent.

3) A line-numbered, unchanging, publicly available copy of the file to be reviewed should be pointed to for 72 hours or more before the review.

4) No design-on-the-fly. If there's a problem, or an issue, note its location, and keep moving.

5) Testing that goes through all paths in the development environment is a very, very, very, good idea. Testing that requires massive external data, hardware resources, use of the customer's site, etc, etc. is testing that costs a fortune and won't be thorough.

6) A non-ASCII file format is acceptable if creation, display, edit, etc., tools exist or are created early in development. This is a personal bias of mine, but in a world where the dominant OS can't get out of its own way with less than 1 gigabyte of RAM, I can't understand why files less than, say, 10 megabytes should be anything other than ASCII or some other commercially supported format. There are standards for graphics, sound, movies, executable, and tools that go with them. There is no excuse for a file containing a binary representation of some number of objects.

For maintenance, refactoring or development of released code, one group of co-workers I had used review by one other person, sitting at a display and looking at a diff of old and new, as a gateway to branch check-in. I liked it, it was cheap, fast, relatively easy to do. Walk-throughs for people who haven't read the code in advance can be educational for all but seldom improve the developer's code.

If you're geographically distributed, looking at diffs on a screen while talking with someone else looking at the same would be relatively easy. That covers two people looking at changes. For a larger group who have read the code in question, multiple sites isn't a lot harder than all in one room. Multiple rooms linked by shared computer screens and squak boxes work very well, IMHO. The more sites, the more meeting management is needed. A manager as facilitator can earn their keep here. Remember to keep polling the sites you're not at.

At one point, the same organization had automated unit testing which was used as regression testing. That was really nice. Of course we then changed platforms and automated test got left behind. Review is better, as the Agile Manifesto notes, relationships are more important than process or tools. But once you've got review, automated unit tests/regression tests are the next most important help in creating good software.

If you can base the tests on requirements, well, like the lady says in "When Harry Met Sally", I'll have what she's having!

All reviews need to have a parking lot to capture requirements and design issues at the level above coding. Once something is recognized as belonging in the parking lot, discussion should stop in the review.

Sometimes I think code review should be like schematic reviews in hardware design- completely public, thorough, tutorial, the end of a process, a gateway after which it gets built and tested. But schematic reviews are heavyweight because changing physical objects is expensive. Architecture, interface and documentation reviews for software should probably be heavyweight. Code is more fluid. Code review should be lighter weight.

In a lot of ways, I think technology is as much about culture and expectation as it is about a specific tool. Think of all the "Swiss Family Robinson"/Flintstones/McGyver improvisations that delight the heart and challenge the mind. We want our stuff to work. There isn't a single path to that, any more than there was "intelligence" which could somehow be abstracted and automated by 1960s AI programs.

OwnerDisplayName: Bill IV


答: If you want people's code to be more standardized, without making them "waste their time on formatting", as some developers will complain about. Invest in a tool like ReSharper as it makes fixing formatting and other re-factoring tasks an almost automated process.</p>

OwnerDisplayName: Chad


答:
If a machine can check it, people shouldn't.

Only one checklist item: Is every error case handled correctly everywhere?

Use code reviews to improve quality and transfer knowledge.

Don't use code reviews to identify "bad" developers.

Ego dings are more effective than explicit points.

Keep it short - 90 minutes and 500 lines is HUGE.

OwnerDisplayName: wowest


答:
I think your grading system is a bad idea. What is the point? To identify good and bad programmers? Everyone in that code review can form an assessment about a particular programmer based on the code presented in the code review better than some arbitrary assignment of values to a somewhat arbitrary set of characteristics. If you want to identify good and bad programmers...ask the programmers. I guarantee humans can do this assessment better than your silly heuristic.

My suggestion would be to try and improve code reviews so that people share ideas and opinions openly in a non-judgmental and non-hostile environment. If you could do that, you'll be 100X better off than casting judgments on programmers based on your silly checklists which purport to do a good job of assessing programmers. I think a lot of programmers are already proud and hard on themselves if they do poorly in code reviews; I question whether further 'punishment' for poor performance is generally helpful.

OwnerDisplayName: robarson


答:
I actually care more about the "subjective" stuff than anything else, frankly.  What I want from a good code review is someone to check my logic, not my typing.  And that's what I focus on when I give a code review.

The general format I like to take is:

What are we fixing?

What was causing it?  (look at the code)

How are we fixing it?

Show me the new code

Show me the code working

Without that, just looking at diffs tends to give input on minor issues or stylistic points.  I'm far more concerned with whether the logic is correct, the approach used overall is good, and whether the solution will be maintainable.

As an example, I recently looked at some code by a co-worker.  The original issue was an FxCop violation.  But what was being done was attempting to determine the presence or absence of a Windows feature by checking the version number.  My main input was that this was a fragile way to do so, and we'd be better off querying the service directly, as the mapping between feature existence and Windows sku could change in the future, and was not future-proof at all.

OwnerDisplayName: kyoryu


答: If you can measure it, if it's objective, quantifiable, then try to have a tool do it. Where you need an experienced reviewer is for the fuzzy subjective stuff.</p>

OwnerDisplayName: kiwicptn


答:
A lot of good comments have already been made on issues of style, which is important.  On a team project, it is valuable for all the code to look like it was written by a single author.  This makes it easier for other members of the team to drop in and fix problems when they occur.  What quantitative measures you choose to ensure this broader goal are less important.

One additional item is ensuring that the code matches up with the overall architecture that has been agreed upon for the rest of the system.  Similar problems should all be solved the same way.  If the application logic has been split across layers, does the code being reviewed break apart it's functionality the way that the rest of the system does?  Alternatively, does the code under review teach something new that should be pulled back across the rest of the system?  Just like the style checks ensure the code all looks the same, the architecture review should ensure that the code all works the same way.  The emphasis here again is on maintainability.  Anyone on the team should be able to drop into this code and have a grasp of what is happening right away.

The grading idea seems like a disaster in the making, but you know your team best. It's possible that they will be motivated by such a system, but I think it more likely that people will start to worry more about their grade than solving problems.  One of the really valuable side effects of code reviews is the mentoring opportunities they offer.  The reviewer should treat the person who wrote the code as someone they are mentoring.  Each issue found is not a problem, but an opportunity to create a more knowledgeable and sophisticated team member and a more tightly knit team overall.

OwnerDisplayName: Jim Blanchard


答: I could write a few paragraphs, but I would only gloss over what Karl Wiegers explains in "Peer Reviews in Software: A Practical Guide". I think that his book contains explicit and concise answers to your question (and much more).</p>

OwnerDisplayName: CesarGon


问:
How could dependency injection be integrated into the language?
I've been thinking a bit on how dependency injection could be better integrated directly into a C# like language. I've come up with  a potential solution I'd like to hear your opinion on. I haven't used many dependency injection frameworks so there might be something I'm overlooking

Anyways, the idea is to be able to declare properties as "injectable" using a keyword. When an object is instantiated, and that property is not initialized through the constructor, or object initializer, it requests an instance of that property type from some global service.

Similarly you register handlers for different types to that service so that you can instantiate the injected property type.

The upside of using this kind of architecture IMO is that it's fairly flexible and easy to use. The downside is that there might be some overhead of doing the callout to the singleton each time you initiate a class that has injection.

Then again that's only an issue for classes that get's instantiated frequently in a high performance solution so it shouldn't be much of an issue. Perhaps you could use some kind of factory in those instances.

Thought, issues, questions, better ideas?

Code

```<code>public class SomeClass
{

  public SomeClass()
  {
     //implicit behavior if Animal is not set in constructor or initializer
    this.Animal =  GlobalInjector.Get(this,typeof(Mammal))

  }

  public injectable Mammal Animal
  {
   get;
   set;
  }
}

 GlobalInjector.Register(typeof(Mammal), () => return new Mammal(someParameter));
</code>```

答:
It isn't needed

One of the things I like best about the best DI frameworks I've used is that the top-level configuration code is the only part of your code that needs to know about DI.  Auto-wiring is done at the container and configuration/"module-loading" level, and your application code can be completely oblivious to it.

This means no attributes, no magic strings, no convention.  Each piece of code only knows that it accepts code in its constructor (/properties/methods), and that's all.

With a design like that you don't need to alter the language at all to support Dependency Injection.

It is potentially dangerous

The thing I fear most about a language-integrated dependency injection system is that it would raise a barrier against any other implementation, yet it would probably paint itself into a corner in some aspect.

Some ways it could paint itself into a corner:

Only supporting XML-based configuration, or only code-based configuration

Not being able to cleanly support the Factory design pattern (not just transient components: run-time generated components)

Somehow changing my code so I was forced to use dependency injection, and couldn't simply instantiate my class for unit tests

Not supporting custom lifecycles

Not being extensible

Not being replaceable in cases where I need greater customization

Being broken in some way that we don't understand yet, because us .Net users haven't been using DI long enough to know the pitfalls


问:
At what point should you switch to release build?
One of the practices set out in Jez Humble's Continuous Delivery is that you should build one package and then release it to each environment you deploy to, so that the deployment and the artifacts have themselves been tested multiple times before going to production.

I fully support this idea.

On the other hand, debug-mode builds that give you stack traces with line numbers are incredibly useful in test environments, as is the ability to remote-debug. But, you want to send a release build to production.

So, for people following the first principle, at what point do you switch from debug to release builds?

Is it before the first deployment to a test environment, figuring the cost of losing debug mode is worth paying to ensure you are testing the actual release candidate early? Or do you build again at some point in the promotion process, figuring that you'll trust the build process over the software? Or do you just screw it all and deploy debug versions to production?

Note: I know this doesn't really apply to interpreted languages because you can usually flick the switch in configuration rather than doing it at build time.

答:
So, for people following the first principle, at what point do you switch from debug to release builds?

We switch early, when the source code got a version number and got pushed into the Debian build queue. We are in the lucky situation of doing scientific software with well-specified inputs and outputs and little system interaction, though, so the cost of reproducing an error situation is fairly low.

This is also my general answer: The point of changing builds depends mostly on the reproduction costs for errors. If these are very high, I'd even ship debug builds to test customers. While that carries the risk of build failures for the production build, this could still be cheaper than spending weeks in test case reproduction.


问:
Should one comment differently in functional languages?
I'm just getting started with functional programming and I'm wondering about the correct way to comment my code.

It seems a little redundant to comment a short function as the names and signature already should tell you everything you need to know. Commenting larger functions also seems a little redundant since they are generally comprised of smaller self-descriptive functions.

What is the correct way to comment a functional program? Should I use the same approach as in iterative programming?

答:
The comment itself shouldn't contain an alternative description to what the code does (that actually is expressed by the code itself), but rather an explaination of the reasons why the code is written the way it is.

That said, I don't see any reason why a comment should per se be different in a functional language.


答:
There definitely is a point in this question, as functional programs usually are on a different abstraction level than imperative ones.

Because of this, another style of documentation is needed. In iterative programs a comment may be helpful like in the following code, because the essence of the code is hidden behind boilerplate:

```<code>// map 'toUpperCase' over 'container' yielding 'result'
Container result = new Container();
for (int i=0; i < container.size(); i++) {
             result.addToTail(container.atElement(i).toUpperCase());
}
</code>```

But this is clearly nonsense in a functional language:

```<code>-- map 'toUpperCase' over 'list'
let result = map toUpperCase list
</code>```

Better:

```<code>-- we need the FooBars in all uppercase for the Frobnitz-Interface
let result = map toUpperCase list
</code>```

Title: Should one comment differently in functional languages?

Body:
I'm just getting started with functional programming and I'm wondering about the correct way to comment my code.

It seems a little redundant to comment a short function as the names and signature already should tell you everything you need to know. Commenting larger functions also seems a little redundant since they are generally comprised of smaller self-descriptive functions.

What is the correct way to comment a functional program? Should I use the same approach as in iterative programming?

Body:
There definitely is a point in this question, as functional programs usually are on a different abstraction level than imperative ones.

Because of this, another style of documentation is needed. In iterative programs a comment may be helpful like in the following code, because the essence of the code is hidden behind boilerplate:

// map 'toUpperCase' over 'container' yielding 'result'
Container result = new Container();
for (int i=0; i < container.size(); i++) {
             result.addToTail(container.atElement(i).toUpperCase());
}

But this is clearly nonsense in a functional language:

-- map 'toUpperCase' over 'list'
let result = map toUpperCase list

Better:

-- we need the FooBars in all uppercase for the Frobnitz-Interface
let result = map toUpperCase list


问:
Does calling a virtual protected method from a base class violate the LSP?
Let's say we have this base class:

```<code>class MyBase
{
    public string Name { get; set; }

    public string GetDescription()
    {
        var descriptionList = new List<string>() { this.Name };
        descriptionList.AddRange(this.ExtraDescriptions.ToList());
        return string.Join(", ", descriptionList();
    }

    protected virtual IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>();
    }
}
</code>```

Then add a derived class:

```<code>class MyDerived : MyBase
{
    protected override IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>() { "a", "b" };
    }
}
</code>```

It seems to me that this violates the LSP (because we're changing the behavior of the GetDescription method), and yet it's also a fundamental feature of object-oriented programming.  The base class obviously declares its intention to allow the ExtraDescriptions method to be overridden, but this isn't necessarily visible to a consumer of the class.

Ever since I learned about the LSP, this problem has really been gnawing at me.  So:

Does this violate LSP?

What's the correct alternative to this?

答:
It is valid and called template method pattern. It is useful to reduce sequential coupling.

As an alternative, you can use closures, metaprogramming or patterns like policy.

see : http://sourcemaking.com/design_patterns/template_method for template method pattern and many others.


答:
I think it depends on what is the expected (published / documented) behaviour / contract of the base class / interface.

If GetDescription is meant to return some general, loosely defined description text (comma-separated list of words), it is perfectly fine for different derived classes to add different items to its output via overriding ExtraDescriptions. This is the Template Method pattern in action. [Update] In other words, LSP is not violated in this case.[/Update]

If OTOH it is declared to always return the name of the object and nothing else, using a Template Method to open up a possibility of breaking the interface contract wouldn't make the slightest sense. [Update] In other words, LSP would be violated in this case.[/Update]

Title: Does calling a virtual protected method from a base class violate the LSP?

Body:
Let's say we have this base class:

```<code>class MyBase
{
    public string Name { get; set; }

    public string GetDescription()
    {
        var descriptionList = new List<string>() { this.Name };
        descriptionList.AddRange(this.ExtraDescriptions.ToList());
        return string.Join(", ", descriptionList();
    }

    protected virtual IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>();
    }
}
</code>```

Then add a derived class:

```<code>class MyDerived : MyBase
{
    protected override IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>() { "a", "b" };
    }
}
</code>```

It seems to me that this violates the LSP (because we're changing the behavior of the GetDescription method), and yet it's also a fundamental feature of object-oriented programming.  The base class obviously declares its intention to allow the ExtraDescriptions method to be overridden, but this isn't necessarily visible to a consumer of the class.

Ever since I learned about the LSP, this problem has really been gnawing at me.  So:

Does this violate LSP?

What's the correct alternative to this?


问:
Easter eggs as IP protection in software
I work in embedded software, and for some reason, management wants to hide an Easter egg as means of IP protection. They call it a watermark, and since our software interact with the video preview feed (the image displayed on a screen before you take a photo), they want me to implement a trigger which will react to some unusual video input (a video konami code like dark - bright - dark - bright - whatever). When this trigger fires, something strange happens (which is outside of the normal behavior of the software).

The goal is to check whether our software is included in a device. Does it sound like a good idea? I have many argument against this move:

What if the konami code is too sensitive and user triggers it?

Does this kind of watermark have any legal value?

What if this "feature" is discovered by the client?

The performance penalty should be very small, since the soft run on small devices.

I am the one developping this trigger. If things go wrong, what is my responsibility?

What is your opinion about this method? I can't find a link, but I remember seeing an answer on this site suggesting that putting Easter eggs for protection purpose was a good idea. Has anyone tried it with good results?

答:
There is at least one precedent, as described on the Wikipedia article on Easter eggs:

The CVAX microchip implementation of the MicroVAX cpu contained in its etchings the Russian phrase in the Cyrillic alphabet "VAX: When you care enough to steal the very best" in an effort to needle potential intellectual property-stealing clone manufacturers in the Soviet Bloc.

A little bit more detail on this, can be found on this article on CVAX (which is the reference to the above quote):

Finally, the scribe lane contained the Cyrillic motto "VAX: When you care enough to steal the very best". In 1983, an Unnamed Intelligence Agency had given me the wording, saying that they got it off a purloined VAX-11/780 that was running a Soviet SS20 missile complex. Knowing that some CVAX's would end up in the USSR, the team wanted the Russians to know that we were thinking of them.

As per your specific questions:

What if the konami code is too sensitive and user triggers it?

The Konami code is too well known, hence the possibility of a user triggering it is larger. If you go through with the Easter egg, you should choose an original (and larger) sequence. Since your Easter egg is supposed to be a protection mechanism instead of mindless fun, it'd be best if the sequence wasn't known outside of your company.

Does this kind of watermark have any legal value?
  I am the one developping this trigger. If things go wrong, what is my responsibility?

Consult a lawyer. It highly depends on your locale and the specifics of your contract. In any case, it'd be best to have some proof in written form that the management explicitly asked for the Easter egg. An exchange of emails where it's shown that you raised some concerns should be enough.

What if this "feature" is discovered by the client?

Depends on the client. Some might laugh, some might sue. My opinion is that since the Easter egg is included as means of IP protection, the client should be informed as for every other feature you build for him / her.

The performance penalty should be very small, since the soft run on small devices.

Yes it should, obviously. If you find out that implementing the Easter egg has a measurable performance penalty, that'd be the best reason to not do it.

I have no opinion either way. If you consult a lawyer and cover all your legal bases, go for it, it will probably be useless but you never know.

Update: The CVAX example is of course a hardware example, but I think there aren't any more relevant examples (for software and / or embedded software) that I know of. I've based the answer around it mostly to answer the Has anyone tried it part of the question. I've searched around for other examples, didn't found any and now I have something of an opinion:

It's probably not a very good idea. (not the Easter egg part, the means of IP protection part). Since the idea is neither original nor innovative (the contexts may be different but similar), if it worked there would be at least a few examples out there.


答: The base class, not the derived class is responsible for LSP. So the creator of the base class should make his class open for substitution. This means that if the base class makes a method virtual, it should be overridable by any function without changing the <s>functionality</s> desirable properties of the class.</p>


答:
Based on @deadalnix and @PeterTorok's answers, here is, I think, a better implementation that doesn't violate LSP:

```<code>abstract class AbstractBase
{
    public string Name { get; set; }

    public string GetDescription()
    {
        var descriptionList = new List<string>() { this.Name };
        descriptionList.AddRange(this.ExtraDescriptions().ToList());
        return string.Join(", ", descriptionList();
    }

    protected abstract IEnumerable<string> ExtraDescriptions();
}

class DefaultImplementation : AbstractBase
{
    protected override IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>() { };
    }
}

class OtherImplementation : AbstractBase
{
    protected override IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>() { "a", "b" };
    }
}
</code>```

I also think you could do what @deadalnix said in a comment, which is move the default implementation into the abstract class, like this:

```<code>abstract class AbstractBase
{
    public string Name { get; set; }

    public string GetDescription()
    {
        var descriptionList = new List<string>() { this.Name };
        descriptionList.AddRange(this.ExtraDescriptions().ToList());
        return string.Join(", ", descriptionList();
    }

    protected virtual IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>() { };
    }
}

class DefaultImplementation : AbstractBase
{
}

class OtherImplementation : AbstractBase
{
    protected override IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>() { "a", "b" };
    }
}
</code>```

This allows any overriding class to re-use the default implementation.

Body:
Based on @deadalnix and @PeterTorok's answers, here is, I think, a better implementation that doesn't violate LSP:

abstract class AbstractBase
{
    public string Name { get; set; }

    public string GetDescription()
    {
        var descriptionList = new List<string>() { this.Name };
        descriptionList.AddRange(this.ExtraDescriptions().ToList());
        return string.Join(", ", descriptionList();
    }

    protected abstract IEnumerable<string> ExtraDescriptions();
}

class DefaultImplementation : AbstractBase
{
    protected override IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>() { };
    }
}

class OtherImplementation : AbstractBase
{
    protected override IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>() { "a", "b" };
    }
}

I also think you could do what @deadalnix said in a comment, which is move the default implementation into the abstract class, like this:

abstract class AbstractBase
{
    public string Name { get; set; }

    public string GetDescription()
    {
        var descriptionList = new List<string>() { this.Name };
        descriptionList.AddRange(this.ExtraDescriptions().ToList());
        return string.Join(", ", descriptionList();
    }

    protected virtual IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>() { };
    }
}

class DefaultImplementation : AbstractBase
{
}

class OtherImplementation : AbstractBase
{
    protected override IEnumerable<string> ExtraDescriptions()
    {
        return new List<string>() { "a", "b" };
    }
}

This allows any overriding class to re-use the default implementation.


答:
LSP only requires that a property of a super-class be true of all its derivatives. By "property", in this context, we mean that "it will supply a list of descriptions". The implementation of that is irrelevant.

As far as I can see, there is no violation in your case.

Properties in LSP are much more about the assumptions that can be made by the calling code than they are about the implementation of functionality, or even behaviour.

The canonical example is "a square is a specialised rectangle." But rectangles have height and width properties, which calling code may assume are independent of each other. While a square only really has one dimension, so if I say rect.X = 3; rect.Y = 2; and the object is a rectangle, I get a 3x2 rectangle; but with the same calling code on a square, I get a 2x2 rectangle.


答: At age 25 you tend to remember things much better. As you get older and you are involved with multiple systems with legacy code (yes, the code you write today will be legacy code in 10-15 years) it can be very helpful if there are comments.</p>


答:
If you were a vendor for a manufacturer, I would expect this to be disclosed as it is "outside of the normal behavior of the software".

If your client is the end user, it would depend on what the software does when the "code" is entered.

Title: Easter eggs as IP protection in software

Body:
I work in embedded software, and for some reason, management wants to hide an Easter egg as means of IP protection. They call it a watermark, and since our software interact with the video preview feed (the image displayed on a screen before you take a photo), they want me to implement a trigger which will react to some unusual video input (a video konami code like dark - bright - dark - bright - whatever). When this trigger fires, something strange happens (which is outside of the normal behavior of the software).

The goal is to check whether our software is included in a device. Does it sound like a good idea? I have many argument against this move:

What if the konami code is too sensitive and user triggers it?

Does this kind of watermark have any legal value?

What if this "feature" is discovered by the client?

The performance penalty should be very small, since the soft run on small devices.

I am the one developping this trigger. If things go wrong, what is my responsibility?

What is your opinion about this method? I can't find a link, but I remember seeing an answer on this site suggesting that putting Easter eggs for protection purpose was a good idea. Has anyone tried it with good results?


答:
The function name should say what you're doing.

The implementation will tell you how you're doing it.

Use comments to explain why you're doing it.


问:
When will be your project finished? How long does it take to complete it? Any idea how do you estimate such timing on the spot?

Possible Duplicate:

  How to respond when you are asked for an estimate?

In my company, i have a strange managers, they always asks me before starting how is it going? And how long it will take to finish? From Day 1 to end of the project life. Behind the screen they do not have any idea what language i will  need to use. I was myself forced to use PHP, C, Java, Vala, D, Bash, many other platforms etc etc, where i was only a Visual basic 6.0 programmer.

But it takes me lot of time to complete a project, because i care about it before releasing, requires lot of testing etc etc.

The problem is, i still do not have any best answer when someone asks me "how long do you think it will take to finish this project?", although i have done lot of projects. But i can not answer such questions, because in my mind its never finished, i always wanted to do more and more optimized code even after release.

I would like to know how you guys tangle this question? (as pro-programmer way)

答:
You should refuse to estimate on the spot.

If you must, always qualify your answer as something that can be 2 orders of magnitude off, either way.

Insist that for a better estimate you need time to evaluate the project properly.


答:
Ok, firstly, what you are doing doesn't necessarily violate LSP, if I understand the context correctly. The LSP reads:

Let q(x) be a property provable about objects x of type T. Then q(y)
  should be provable for objects y of type S where S is a subtype of T.

Now let's translate that to classes:

Let q(x) be a property of all instances x of class T. Then q(y)
  should also be a property of all instances y of any class S that is a subclass of T.

Now given the context, that q here is basically: a call to the object's GetDescription-method will return a meaningful description of that object.

In this case you're not violating it. On the contrary, one could argue that you're actually enforcing it, because if you did not override the method accordingly, then the result of GetDescription would in fact not be meaningful and thus LSP would not hold.

To contrast this, here's a real violation:

```<code>class MyUndescribable : MyBase
{
    override public string GetDescription()
    {
        throw "can't touch this!";
    }
}
</code>```

I would argue that applying the LSP to non-public members is a bit pointless, because you making any assumptions about non-public members of an instance means violating encapsulation. The only time where this is worth considering is, when an instance of A calls a protected method of another instance of A (which could actually be an instance of a class B that has overridden this method).

Secondly, what you are doing would be better achieved through composition, following the DIP. The logic from ExtraDescriptions should be passed in, either as a function object, or as an abstract service. This way you could still derive MyDerived from MyBase (if you really wanted), and pass the logic to the super constructor for example. Thus MyDerived would be further decoupled from MyBase.

Body:
Ok, firstly, what you are doing doesn't necessarily violate LSP, if I understand the context correctly. The LSP reads:

Let q(x) be a property provable about objects x of type T. Then q(y)
  should be provable for objects y of type S where S is a subtype of T.

Now let's translate that to classes:

Let q(x) be a property of all instances x of class T. Then q(y)
  should also be a property of all instances y of any class S that is a subclass of T.

Now given the context, that q here is basically: a call to the object's GetDescription-method will return a meaningful description of that object.

In this case you're not violating it. On the contrary, one could argue that you're actually enforcing it, because if you did not override the method accordingly, then the result of GetDescription would in fact not be meaningful and thus LSP would not hold.

To contrast this, here's a real violation:

class MyUndescribable : MyBase
{
    override public string GetDescription()
    {
        throw "can't touch this!";
    }
}

I would argue that applying the LSP to non-public members is a bit pointless, because you making any assumptions about non-public members of an instance means violating encapsulation. The only time where this is worth considering is, when an instance of A calls a protected method of another instance of A (which could actually be an instance of a class B that has overridden this method).

Secondly, what you are doing would be better achieved through composition, following the DIP. The logic from ExtraDescriptions should be passed in, either as a function object, or as an abstract service. This way you could still derive MyDerived from MyBase (if you really wanted), and pass the logic to the super constructor for example. Thus MyDerived would be further decoupled from MyBase.


问:
Is there a name for "More events than expected" bug?
Is there a name for a family of bugs, that are caused by assumption, that user would generate only 1 event during the execution of the handler ?

Simplest example is: animation triggered by click, which can run several copies of itself, if user rapidly clicks several times.

答:
I don't know if there is a general accepted term for it. However, i would have named it as

event flood  OR

trigger chain


答:
So, for people following the first principle, at what point do you switch from debug to release builds?

As soon as we go to QA we switch to release builds. But when ever we build a release build our build process also builds a debug version of the dlls. This allows us to quickly drop the debug dlls into the QA environment and get additional information if required.

Both the release and debug versions of the dlls are backed up and kept for several years.

Title: At what point should you switch to release build?

Body:
One of the practices set out in Jez Humble's Continuous Delivery is that you should build one package and then release it to each environment you deploy to, so that the deployment and the artifacts have themselves been tested multiple times before going to production.

I fully support this idea.

On the other hand, debug-mode builds that give you stack traces with line numbers are incredibly useful in test environments, as is the ability to remote-debug. But, you want to send a release build to production.

So, for people following the first principle, at what point do you switch from debug to release builds?

Is it before the first deployment to a test environment, figuring the cost of losing debug mode is worth paying to ensure you are testing the actual release candidate early? Or do you build again at some point in the promotion process, figuring that you'll trust the build process over the software? Or do you just screw it all and deploy debug versions to production?

Note: I know this doesn't really apply to interpreted languages because you can usually flick the switch in configuration rather than doing it at build time.


答:
I see nothing wrong with an undisclosed easter egg as long as it extremely unlikely a user will run into it and if it is extremely subtle.  If somebody were to stumble across it then they shouldn't view it as anything different than a subtle glitch or cosmetic trivial bug.

I have had managers argue with me for functionality that is far less ethical than an undisclosed easter egg, borderline malware stuff so I have trouble viewing this as an issue.

In one project I inherited I discovered a gigantic misleading C# class, named something to the effect, UIDataTableColumnRenderer that was over 3mb in size.  I discovered an entire mini-game within that class, images and all base64 encoded into strings within the class.  It was basically a shooter where the PC was a developer trying to shoot down a relentless onslaught of bugs and poorly written requirements that PM's and product owners were throwing at the software.  It was kind of funny in that it kept getting harder and harder and you never win, eventually the bugs and poor requirements destroy the software and the PC loses his job.

It was by far the most stunning easter egg I have ever found.


问:
How to improve your ability to debug existing code
A common task in the working world is dealing with existing, but buggy code. What are some tips to improve your skills as a debugger?</p>

答: If you've narrowed it down to a small region, but can't still can't spot the error, try the 'view code + assembly' option of your debugger.  Knowing enough ASM to say "there should be a branch here" or "why is it only copying the low word?" will often pinpoint the coding error.  </p>


问:
Big table with referential integrity or field typification?
I'm using an ORM (Propel) and PHP to create Objects and store them in a database. So, I'm facing a recurrent problem and I'm pretty sure this happened to someone before.

My data model looks something like this:

So class A needs a reference to something from the hierarchy of Clase Parent (abstract class), this is not the problem. The idea behind this solutions is that in the future it would be very easy to create new strategies. But remember I said I'm using an ORM to store info in the database?

Well, the database has 3 tables: A_table, B_table and C_table. So here comes the situation:

A_table needs to be related to the strategy. Whats the best way to go?

Create a strategy type reference table, assosiate a type to the A_table and have a relation_id thats just an intenger with a value (no referential integrity whatsoever)

Create one field per strategy in the A_table, and allow them to be null

Really looking forward for opinions and why its best one or the other.

答:
I faced a similar problem, using NHibernate as my ORM.  In that case, I created a separate table for Parent with just an Id column in it.  Then I created one-to-one relationships between B and Parent and C and Parent.  So, for every record in B or C there is a corresponding record in Parent.  You do this by making your primary keys in B and C also foreign keys referencing Parent. Then I could create a normal foreign key relationship between A and Parent.

That has 2 advantages:

It's easy to add new strategies

It's easy to add properties to the Parent class, if necessary

Of course, you end up with one more table, but I found that the ORM made it all transparent.


问:
Is it good practice to use functions just to centralize common code?
I run across this problem a lot. For example, I currently write a read function and a write function, and they both check if buf is a NULL pointer and that the mode variable is within certain boundaries.

This is code duplication. This can be solved by moving it into its own function. But should I? This will be a pretty anemic function (doesn't do much), rather localized (so not general purpose), and doesn't stand well on its own (can't figure out what you need it for unless you see where it is used). Another option is to use a macro, but I want to talk about functions in this post.

So, should you use a function for something like this?
What are the pros and cons?

答:
It's almost always good if following conditions are met:

improves readability

used within limited scope

In larger scope you must carefully weigh duplication vs dependency trade-offs. Examples of scope limiting techniques: hiding in private sections or modules without exposing them public.


问:
How to choose an agile methodology?
I'm working in a little firm about 10 developpers,
we are working a kind of agile way but knowledgeless and without formalism.
I think be aware of what are agile method, what can they afford to us, may render more productive our products.
However there is a lot of agile method, which could be the simplest to "learn"?

Rapid Application Development

Dynamic systems development method

Scrum

Feature Driven Development

Extreme programming

Adaptive software development

Test Driven Development

Crystal clear

答:
I would suggest that you don't use get stuck to a particular methodology. Instead, pick and choose practices that help you and add them into your existing work.

I would look at

Just explore web sites, see if there is a practice that might help you, try it out

Technical practices like unit testing, automated tests, continuous integration are v. useful. Investigate these.

Regularly (about twice a month) sit down and see what you did well and where you can improve

Work feature by feature. What I mean is, implement one feature, test it, deploy it. Then start with the next feature. Dont work on many features at once

Try to spread around knowledge. Let different people work on different parts of the application. Don't have a situation where only certain people always work on the same components everytime

Focus on feedback. Try to have access to a customer or user or domain expert who can look at what you are doing and give you feedback often

OwnerDisplayName: Christophe Debove

Title: How to choose an agile methodology?

OwnerDisplayName: Siddharta


答:
We have our developer machines set up to build debug builds.  But once the devs commit code, a deployment package is created in our continuous integration environment (TeamCity) and that is built for release.  So whenever we decide to deploy to QA, we take the latest deployment package from the CI server and push it out, so it is always release unless it is on a dev machine.

BTW, for some languages, even when building for release, you can still create debug symbols.  In .NET, for example, there is a "pdb-only" setting which allows for optimizations but still creates debug files.  Obviously debugging against a release version is trickier since it isn't line-for-line equivalent, but it can still be helpful in a pinch.


答:
What you have described is an excellent example of a...

Race Condition

A race condition (applicable to both electronics and with programming) is when "the output and/or result of the process is unexpectedly and critically dependent on the sequence or timing of other events."

You have also described an issue with...

Reentrancy

In general, methods that may safely directly or indirectly call themselves are re-entrant.  If your event handlers are inadvertently raising other events that you cannot safely handle, you can say that you have non-reentrant code.

In C#, here is an example of code that exhibits a race condition:

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (timer1.Enabled)
        throw new InvalidOperationException("We're already ticking, you really should wait!");

    timer1.Interval = 5000;
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    MessageBox.Show("Okie Dokie");
    timer1.Stop();
}
</code>```

Here is a simple example of code that exhibits a problem with reentrancy:

```<code>private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
    //move to the next cell if we are in the first cell
    if (dataGridView1.CurrentCell != null &&
        dataGridView1.CurrentCell.RowIndex == 0 &&
        dataGridView1.CurrentCell.ColumnIndex == 0)
    {
        //this throws an InvalidOperationException because the Microsoft DataGridView
        //does not handle Re-entrant calls to SetCurrentCellAddressCore
        dataGridView1.CurrentCell = dataGridView1[1, 0];
    }
}
</code>```

There are a number of ways to solve these types of problems.  Two ways are through mutual exclusion ( such as with locking) or by avoiding the race condition or re-entrancy altogether.

Simple solution to example #1 using mutual exclusion:

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (timer1.Enabled)
        return; //just silently ignore, maybe throw up a message box

    timer1.Interval = 5000;
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    MessageBox.Show("Okie Dokie");
    timer1.Stop();
}
</code>```

Nitpicker's corner: locking is not necessary in this case because all code is running on the UI thread.

Here's a solution to example #2 that avoids the issue altogether:

```<code>private void button1_Click(object sender, EventArgs e)
{
    Timer newTimer = new Timer() { Interval = 5000 };
    newTimer.Tick += new EventHandler(newTimer_Tick);
    newTimer.Start();
}

void newTimer_Tick(object sender, EventArgs e)
{
    MessageBox.Show("Okie Dokie");
    ((Timer)sender).Dispose();  //probably not great to dispose in the middle of an eventhandler, but you get the idea...
}
</code>```

Here's a solution to example #3 that avoids the re-entrancy issue:

```<code>private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
    //move to the next cell if we are in the first cell
    if (dataGridView1.CurrentCell != null &&
        dataGridView1.CurrentCell.RowIndex == 0 &&
        dataGridView1.CurrentCell.ColumnIndex == 0)
    {
        //this does not throw an exception because
        //the CurrentCell will be set some time later
        dataGridView1.BeginInvoke(new MethodInvoker(() =>
            {
                dataGridView1.CurrentCell = dataGridView1[1, 0];
            }));
    }
}
</code>```

Title: Is there a name for "More events than expected" bug?

Body:
Is there a name for a family of bugs, that are caused by assumption, that user would generate only 1 event during the execution of the handler ?

Simplest example is: animation triggered by click, which can run several copies of itself, if user rapidly clicks several times.

Body:
What you have described is an excellent example of a...

Race Condition

A race condition (applicable to both electronics and with programming) is when "the output and/or result of the process is unexpectedly and critically dependent on the sequence or timing of other events."

You have also described an issue with...

Reentrancy

In general, methods that may safely directly or indirectly call themselves are re-entrant.  If your event handlers are inadvertently raising other events that you cannot safely handle, you can say that you have non-reentrant code.

In C#, here is an example of code that exhibits a race condition:

private void button1_Click(object sender, EventArgs e)
{
    if (timer1.Enabled)
        throw new InvalidOperationException("We're already ticking, you really should wait!");

    timer1.Interval = 5000;
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    MessageBox.Show("Okie Dokie");
    timer1.Stop();
}

Here is a simple example of code that exhibits a problem with reentrancy:

private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
    //move to the next cell if we are in the first cell
    if (dataGridView1.CurrentCell != null &&
        dataGridView1.CurrentCell.RowIndex == 0 &&
        dataGridView1.CurrentCell.ColumnIndex == 0)
    {
        //this throws an InvalidOperationException because the Microsoft DataGridView
        //does not handle Re-entrant calls to SetCurrentCellAddressCore
        dataGridView1.CurrentCell = dataGridView1[1, 0];
    }
}

There are a number of ways to solve these types of problems.  Two ways are through mutual exclusion ( such as with locking) or by avoiding the race condition or re-entrancy altogether.

Simple solution to example #1 using mutual exclusion:

private void button1_Click(object sender, EventArgs e)
{
    if (timer1.Enabled)
        return; //just silently ignore, maybe throw up a message box

    timer1.Interval = 5000;
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    MessageBox.Show("Okie Dokie");
    timer1.Stop();
}

Nitpicker's corner: locking is not necessary in this case because all code is running on the UI thread.

Here's a solution to example #2 that avoids the issue altogether:

private void button1_Click(object sender, EventArgs e)
{
    Timer newTimer = new Timer() { Interval = 5000 };
    newTimer.Tick += new EventHandler(newTimer_Tick);
    newTimer.Start();
}

void newTimer_Tick(object sender, EventArgs e)
{
    MessageBox.Show("Okie Dokie");
    ((Timer)sender).Dispose();  //probably not great to dispose in the middle of an eventhandler, but you get the idea...
}

Here's a solution to example #3 that avoids the re-entrancy issue:

private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
    //move to the next cell if we are in the first cell
    if (dataGridView1.CurrentCell != null &&
        dataGridView1.CurrentCell.RowIndex == 0 &&
        dataGridView1.CurrentCell.ColumnIndex == 0)
    {
        //this does not throw an exception because
        //the CurrentCell will be set some time later
        dataGridView1.BeginInvoke(new MethodInvoker(() =>
            {
                dataGridView1.CurrentCell = dataGridView1[1, 0];
            }));
    }
}


问:
What's wrong with circular references?
I was involved in a programming discussion today where I made some statements that basically assumed axiomatically that circular references (between modules, classes, whatever) are generally bad.  Once I got through with my pitch, my coworker asked, "what's wrong with circular references?"

I've got strong feelings on this, but it's hard for me to verbalize concisely and concretely.  Any explanation that I may come up with tends to rely on other items that I too consider axioms ("can't use in isolation, so can't test", "unknown/undefined behavior as state mutates in the participating objects", etc.), but I'd love to hear a concise reason for why circular references are bad that don't take the kinds of leaps of faith that my own brain does, having spent many hours over the years untangling them to understand, fix, and extend various bits of code.

Edit: I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent.  This question is really asking about "larger scope" circular references, like libA calling libB which calls back to libA.  Substitute 'module' for 'lib' if you like.  Thanks for all of the answers so far!

答:
There are a great many things wrong with circular references:

Circular class references create high coupling; both classes must be recompiled every time either of them is changed.

Circular assembly references prevent static linking, because B depends on A but A cannot be assembled until B is complete.

Circular object references can crash naïve recursive algorithms (such as serializers, visitors and pretty-printers) with stack overflows.  The more advanced algorithms will have cycle detection and will merely fail with a more descriptive exception/error message.

Circular object references also make dependency injection impossible, significantly reducing the testability of your system.

Objects with a very large number of circular references are often God Objects.  Even if they are not, they have a tendency to lead to Spaghetti Code.

Circular entity references (especially in databases, but also in domain models) prevent the use of non-nullability constraints, which may eventually lead to data corruption or at least inconsistency.

Circular references in general are simply confusing and drastically increase the cognitive load when attempting to understand how a program functions.

Please, think of the children; avoid circular references whenever you can.

Title: What's wrong with circular references?


答: I think scrum is probably the most widely practiced methodology currently, probably because it doesn't prescribe the details of writing software, just how to manage your process.  Then you cherry pick what makes sense for your team from the more programming-specific methodologies like XP.  Scrum also contains a retrospective after every iteration, where you can talk about what you like and don't like about the process and make adjustments to make it fit your team better.  Even the other scrum teams at our company do things somewhat differently than ours, even though we are all practicing "scrum" and started our first iterations very similar to each other.</p>

Title: How to choose an agile methodology?

Body:
I'm working in a little firm about 10 developpers,
we are working a kind of agile way but knowledgeless and without formalism.
I think be aware of what are agile method, what can they afford to us, may render more productive our products.
However there is a lot of agile method, which could be the simplest to "learn"?

Rapid Application Development

Dynamic systems development method

Scrum

Feature Driven Development

Extreme programming

Adaptive software development

Test Driven Development

Crystal clear


问:
Introducing Programming To a Mathematician
I currently am a programmer, I'm almost 16 years of age and have pretty much narrowed my careers down to something involving a Computer Science degree or Electrical Engineering degree (I know they are quite different but this question is about my friend) but my friend isn't so sure.

He is very interested in maths and is very good at it and I think he would enjoy programming but he isn't willing to try it (edit he is willing to try but has never done before). Can anyone give me an suggestions for a language or tool that he could dabble in programming (at a reasonably basic level I assume) to solve maths problems or involve some kind of maths.

As I say he enjoys maths a lot but I think he would enjoy programming, the problem is I don't want him to be put off by the stuff that isn't relevant at introductory levels such as memory allocation et al. I know that is very important but the point is that I want him to learn a bit of programming with maths then hopefully if he is interested enough he can start learning programming as programming.

Edit:
Its not that he's completely uninterested - more that he hasn't actively explored the area before, maybe because he isn't informed about it. I wouldn't want to force him to do something he doesn't want to, I see this as more of a little push so that he can learn about programming. If he doesn't like it - fair enough, I can't control that and don't want to but if he turns out to enjoy it - this push will have been the right thing.

答:
Matlab is commonly used for mathematical and scientific programming. It is a script based language, not hard to learn and all the memory issues are hidden from the user.

Software Engineering and Electrical Engineering can be combined into Computer Engineering.


问:
Single click handler for all buttons in Javascript? Is it a pattern? Whats the benefit?
I have been told that when there are multiple buttons on the page for same purpose but targeting different item e.g. delete item on a grid of items, they say it is recommended to just register for click handler only on the top most element like 'body' and check what was clicked instead of hooking up click with every delete button.

Whats the benefit of this? Creating more handlers causes problems? Is it an optimization of some sort? Is it a pattern? Does it have anything to do with performance? Where can I read more about it?

答:
From @good_computer comment

What you're talking about is very well known as Event Delegation --
  it's a very good technique, and there's so much on the Internet about
  this topic that saying it all here would be superfluous. - greengit


问:
Use of Service Bus in a Pub-Sub Engine
In one of our projects, we've built a Publisher - Subscriber Engine on Oracle Service Bus. The functionality being a series of events are published and subscribers (JMS queues) receive these whenever a new event is published.

We are facing some technical issues now, performance-wise and hence an architectural review is underway.

Now for my questions:

Architecturally the ESB has to publish events into a DB and read from the DB which users wish to be notified, then push the event onto their respective queues.

There is a high amount of DB interaction and the question is whether ESB should be having such high amount of interaction with the DB in the first place? Or should there have been some alternate component responsible for doing this.

Alternately is there any non-DB approach in which we can store the events and subscribers? Where else can this application data be held within the ESB context?

答:
You can store the events and subscribers in redis
http://redis.io/

Since Redis is a data structure server. You can use the Hash data structure to keep track each instances of your subscriber by creating a key as the name of the subscriber and storing other important information such as ID, transport, and e.t.c in json format. Same can be done for the events also.

The benefit of using the hash is that you get to retrieve your subscriber information as needed in O(1). You could also make use of the hash structure for linking up subscribers to a particular topic

Title: Use of Service Bus in a Pub-Sub Engine


答: Agile should be a set of tools that you can use to make better software not a set of rules that must be followed.  Pick what works for your team.  Do trial periods to see what works and what does not.  Keep reviewing those and you will be doing Agile Agile project management...</p>

Title: How to choose an agile methodology?


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
supervisor/manager

who cares about you as a person

who encourages laughter


答:
Have you considered event-driven systems, such as Complex Event Processing engines? These are tools designed to handle high volume streaming events. Some support integration with a database for historical correlation and data storage.

A prime example of an open-source CEP engine is Esper, although I believe database integration is part of the commercial Esper Enterprise solution. I haven't used this particular tool before, but have researched and developed with similar applications. I'm not sure what the performance hit of adding the database is, but they are designed for situations with a lot of events being processed quickly and maintaining a high event throughput.

At the very least, perhaps event-driven architectural models might be something you can look at and adapt as necessary to your particular problem.

Title: Use of Service Bus in a Pub-Sub Engine

Body:
In one of our projects, we've built a Publisher - Subscriber Engine on Oracle Service Bus. The functionality being a series of events are published and subscribers (JMS queues) receive these whenever a new event is published.

We are facing some technical issues now, performance-wise and hence an architectural review is underway.

Now for my questions:

Architecturally the ESB has to publish events into a DB and read from the DB which users wish to be notified, then push the event onto their respective queues.

There is a high amount of DB interaction and the question is whether ESB should be having such high amount of interaction with the DB in the first place? Or should there have been some alternate component responsible for doing this.

Alternately is there any non-DB approach in which we can store the events and subscribers? Where else can this application data be held within the ESB context?


问:
What do you do when working with multiple languages with different capitalization schemes?
I'm making a webapp using Django.  The Python convention for naming variables is lowercase_with_underscores, but the Javascript convention is camelCase.  In addition, I've seen many people use lowercase-with-hyphens for CSS identifiers.

Would you suggest using all three naming conventions where appropriate, or picking one and using it, even if the other two recommend something else?  Switching back and forth isn't a huge problem, but it can still be mental overhead.

答: Use the right one for the language.  It helps others when they are maintaining the application, and it helps you context switch between languages quicker as the language you are currently working in looks as it should.</p>


答:
It depends on the conventions of the company, team, or project. There is no right answer, other than to do what the code style guides say. If you are on a multi-langauage project, then the guidelines should specify a language-independent style or what style to follow when writing code in each language.

Personally, I would prefer the style recommended by the language. It's much more natural when interfacing with external libraries written in that language and would be easier to read. However, any existing style conventions on the project should be obeyed first.

Title: What do you do when working with multiple languages with different capitalization schemes?

Body:
I'm making a webapp using Django.  The Python convention for naming variables is lowercase_with_underscores, but the Javascript convention is camelCase.  In addition, I've seen many people use lowercase-with-hyphens for CSS identifiers.

Would you suggest using all three naming conventions where appropriate, or picking one and using it, even if the other two recommend something else?  Switching back and forth isn't a huge problem, but it can still be mental overhead.


问:
Is Ant still in the "mainstream" for Java builds?
We have been slowly replacing batch command files (windows .bat) which were simply jarring up the classes compiled in the developers IDE, with more comprehensive Ant builds (i.e. get from CVS, clean compile, jar, archive, email, etc.)

I've spent a lot of time learning (and debugging issues) with Ant, so I'm most comfortable using it for these tasks.  But I wonder if Ant is still in as wide usage as it was when I first started learning, or whether "the world has moved on" to something newer (and maybe slicker). (I've started to see more Maven build stuff distributed, which I've never used, for example.)

The practical import of this question, is whether I push new developers to learn Ant, or whether they should be learning something else for builds?

I'm never too on top of the trends, so it would be great to hear from other Java developers what they think is the best build tool, and what they think new developers should be learning.

答:
I've been working with Ant and with Maven. In my experience, Maven has a very strong edge over Ant.

All the projects I've seen last 2 or 3 years seem to be using maven. About 3 years ago this made me wonder because maven versions used then (2.0.something) seemed to be quite unreliable and buggy. At some point though (2.1 or 2.2 I don't recall) maven became reliable and after some time spent with it I have changed my mind to opposite. Now, I'd rather be surprised seeing someone who prefers ant over maven.

On a less positive note about maven, my experience with its documentation was not so great so far. I think I've seen a product with documentation worse than that of maven but I can't remember which one (some ancient CSV library iirc).


答: We've been using Maven for several years.  It supports Ant scripting (just like Ant supports BeanShell), so your Ant knowledge may still be useful.  Maven is much more powerful, but it has some additional infrastructure requirements (you'll want an Artifactory or Nexus server to host your builds if you share components among multiple projects).  It's also quite different from Ant, so you can't leverage a lot of your existing knowledge.</p>

Title: Is Ant still in the "mainstream" for Java builds?

Body:
We have been slowly replacing batch command files (windows .bat) which were simply jarring up the classes compiled in the developers IDE, with more comprehensive Ant builds (i.e. get from CVS, clean compile, jar, archive, email, etc.)

I've spent a lot of time learning (and debugging issues) with Ant, so I'm most comfortable using it for these tasks.  But I wonder if Ant is still in as wide usage as it was when I first started learning, or whether "the world has moved on" to something newer (and maybe slicker). (I've started to see more Maven build stuff distributed, which I've never used, for example.)

The practical import of this question, is whether I push new developers to learn Ant, or whether they should be learning something else for builds?

I'm never too on top of the trends, so it would be great to hear from other Java developers what they think is the best build tool, and what they think new developers should be learning.


问:
Is it okay to call exception-triggered debugging "post-mortem debugging"?
I heard the term "post-mortem debugging", and Wikipedia says it's debugging done after the program has crashed.

I often debug Python apps using a debugger that stops execution once an important-enough exception has been raised. Then I can use the debug probe to investigate.

Does this count as "post-mortem debugging"? Because the program doesn't really crash.

EDIT: If the answer is no, then what name would you use for the kind of debugging that I described?

答:
No.  Post-mortem debugging involves using a debugger and a core file or other memory image.  If the program's still running, then it hasn't "died", so it's still pre-mortem.

EDIT: I don't think this technique has a specific name, "breakpointing on exceptions" is the term I'd use, although @Jeremy's suggestion is just as good.


问:
Is ORM an Anti-Pattern?
I had a very stimulating and interessting discussion with a colleague about ORM and its pros and cons. In my opinion, an ORM is useful only in the rarest cases. At least in my experience.

But I don't want to list my own arguments at this time. So I ask you, what do you think about ORM? What are the pros and the cons?

答: Using an ORM instead of learning SQL is a pretty bad idea. If you don't know exactly the kind of SQL being generated, if you don't understand the N+1 problems and how to optimize then it will definitely cause more harm than good. I feel though, that I am much more productive using an ORM. I prefer Rails ActiveRecord, which does not try to pretend that there is no database and doesn't get in your way if you just need to write SQL. I do worry though that some people may trust the idioms they see too deeply, without a deep understanding of what they are doing.</p>

Title: Is ORM an Anti-Pattern?


问:
how to deal with controller mutations
During development process, things are constantly changing (especially in early phases). Requirements change, UI changes, everything changes. Pages that clearly belonged to specific controller, mutated to something completely different in the future.

For example. Lets say that we have website for managing Projects. One page of the website was dedicated to managing existing, and inviting new members of specific project. Naturally, I created members controller nested under projects which had proper responsibility.

Later in the development, it turned out that it was the only page that was "configuring the project" in some way, so additional functionalities were added to it:

editing project description

setting project as a default

...

In other words, this page changed its primary responsibility from managing project members to managing project itself. Ideally, this page should be moved to "edit" action of "projects" controller. That would mean that all request and controller specs need to refactored too. Is it worth the effort? Should it be done?

Personally, I am really starting to dislike the 1-1 relationship between views and controllers. Its common situation that we have 1 page (view) that handles 2 or more different resources. I think we should have views completely decoupled from controllers, but rails is giving us hard time to achieve this.

I know that AJAX can be used to solve this issue, but I consider it an improvisation. Is there some other kind of architecture (other than MVC) that decouples views from controllers?

答:
I often find this problem too. I do a couple of things to fix it;

I stuff as much as i can into the models so i dont clutter my controllers and I usually make it so when you click on a project in /projects (projects#index) it will go straight to /projects/:project_id/members (members#index) instead of the default /projects/:id (projects#show). Reason for this being that the members are the main resource on the page.

OwnerDisplayName: Milovan Zogovic

Title: how to deal with controller mutations

OwnerDisplayName: ADAM


答:
Well, to keep my code organized, I often:

decide to extract some controller logic to a superclass and make controller inherit from it. This way, controllers end up calling method from it and remain clean, avoiding duplication

same thing could be done by including modules in your controllers

an alternative solution would be to use a third part component such as Cells.

Title: how to deal with controller mutations

Body:
During development process, things are constantly changing (especially in early phases). Requirements change, UI changes, everything changes. Pages that clearly belonged to specific controller, mutated to something completely different in the future.

For example. Lets say that we have website for managing Projects. One page of the website was dedicated to managing existing, and inviting new members of specific project. Naturally, I created members controller nested under projects which had proper responsibility.

Later in the development, it turned out that it was the only page that was "configuring the project" in some way, so additional functionalities were added to it:

editing project description

setting project as a default

...

In other words, this page changed its primary responsibility from managing project members to managing project itself. Ideally, this page should be moved to "edit" action of "projects" controller. That would mean that all request and controller specs need to refactored too. Is it worth the effort? Should it be done?

Personally, I am really starting to dislike the 1-1 relationship between views and controllers. Its common situation that we have 1 page (view) that handles 2 or more different resources. I think we should have views completely decoupled from controllers, but rails is giving us hard time to achieve this.

I know that AJAX can be used to solve this issue, but I consider it an improvisation. Is there some other kind of architecture (other than MVC) that decouples views from controllers?

OwnerDisplayName: apneadiving


答:
I agree with others here that Maven seems to have taken over most significant projects that I've looked at.

While Ant is highly flexible, the build file is not standardized, so when you move to a new project or company, the targets are named differently, the file is structured differently, the inter-target dependencies may or may not be established, etc.

With Maven, you also get the benefit of not having to carry binary dependencies (I'm talking about jars) around in your SCM system. Lots of other great Java tools know how to read a Maven POM file (the benefit of standardization), so tools like IDEs can set up a Maven project very quickly, and build tools like Jenkins can easily execute Maven builds.


问:
Should one comment differently in functional languages?
I'm just getting started with functional programming and I'm wondering about the correct way to comment my code.

It seems a little redundant to comment a short function as the names and signature already should tell you everything you need to know. Commenting larger functions also seems a little redundant since they are generally comprised of smaller self-descriptive functions.

What is the correct way to comment a functional program? Should I use the same approach as in iterative programming?

答:
Functions should be commented, if the function name and parameter names alone do not suffice to specify the contract.

```<code>// returns a list of Employees    <-- not necessary
def GetEmployeeList: ...

// returns a list of Employees sorted by last name    <-- necessary
def GetEmployeeList: ...
</code>```

In a nutshell, the contract defines what the function expects and what it guarantees. Strictly speaking, if GetEmployeeList returns a sorted list but does not say so in either the function name or the comment, a consumer of this function must not rely on this behavior. It's an undocumented implementation detail, and the author of GetEmployeeList has the freedom to change this behavior any time.

Body:
Functions should be commented, if the function name and parameter names alone do not suffice to specify the contract.

// returns a list of Employees    <-- not necessary
def GetEmployeeList: ...

// returns a list of Employees sorted by last name    <-- necessary
def GetEmployeeList: ...

In a nutshell, the contract defines what the function expects and what it guarantees. Strictly speaking, if GetEmployeeList returns a sorted list but does not say so in either the function name or the comment, a consumer of this function must not rely on this behavior. It's an undocumented implementation detail, and the author of GetEmployeeList has the freedom to change this behavior any time.


答:
I think Ant on its own is dead in the water; having to specify all of your classpath dependencies manually (depending on your setup) is far too manual and far to error prone. If Ant is used alongside a dependency management tool, such as Ivy, then it retains it's power and removes the need to manually manage your dependencies.

The other problem with Ant when compared to Maven is the lack of standardization, which has been mentioned in other answers. When moving from project to project or job to job, one of the most annoying things I find is having to learn the new standard for different Ant files. Maven's aim of convention over configuration means that two different projects will have very similar structure, making transition between them much easier than with Ant.

As for whether Ant is still mainstream or not, it will depend on the development environment you are working in. If the project is in a small company or a start-up, I would imagine Maven would be the natural choice and time can be taken to invest in the infrastructure, such as an Artifactory. However, large companies will have invested many years and lots of money into their Ant infrastructure (configurations, global build files etc) which will mean they will be less keen on moving away from a technology in which they have invested so much money.


问:
Easter eggs as IP protection in software
I work in embedded software, and for some reason, management wants to hide an Easter egg as means of IP protection. They call it a watermark, and since our software interact with the video preview feed (the image displayed on a screen before you take a photo), they want me to implement a trigger which will react to some unusual video input (a video konami code like dark - bright - dark - bright - whatever). When this trigger fires, something strange happens (which is outside of the normal behavior of the software).

The goal is to check whether our software is included in a device. Does it sound like a good idea? I have many argument against this move:

What if the konami code is too sensitive and user triggers it?

Does this kind of watermark have any legal value?

What if this "feature" is discovered by the client?

The performance penalty should be very small, since the soft run on small devices.

I am the one developping this trigger. If things go wrong, what is my responsibility?

What is your opinion about this method? I can't find a link, but I remember seeing an answer on this site suggesting that putting Easter eggs for protection purpose was a good idea. Has anyone tried it with good results?

答:
I am the one developping this trigger. If things go wrong, what is my responsibility?

They are not asking you to break the law. Your accountability is just to your employer. I would write a careful email stating any concerns you have so those are on the record. Then do you what your boss tells you or quit.


答:
I would hestitate to call something an "anti-pattern" which was first called a pattern by Martin Fowler and has since been embraced in nearly every modern programming language. (See the Wikipedia article on ActiveRecord.)

A good ORM can lead to much less code (and much less repetition) in a project, and nothing is as strongly correlated with bugs as quantity of original code.

ORMs are generally designed to handle the most common use cases for working with databases. Complex queries may still need to be written explicitly. But I would strongly discommend writing explicit queries for every database interaction. In most cases, that's a waste of time.

Title: Is ORM an Anti-Pattern?

Body:
I had a very stimulating and interessting discussion with a colleague about ORM and its pros and cons. In my opinion, an ORM is useful only in the rarest cases. At least in my experience.

But I don't want to list my own arguments at this time. So I ask you, what do you think about ORM? What are the pros and the cons?


答:
This is akin to asking "is a power drill an anti-pattern?". ORMs earned a good place in my toolbox, reducing my boilerplate code and I am still able to use custom SQL if necessary. So if it is an anti-pattern, which pattern does it go against?

My answer is no, there are plenty of mature ORMs out there that make your life a lot easier and makes your code more understandable. This in any way means you don't need to understand SQL, quite the contrary.

Title: Is ORM an Anti-Pattern?