问:
overriding implemented base class methods
I read somewhere that the chain of inheritance breaks when you alter a behavior from derived class. What does "altering a behavior" mean here? Is overriding an already implemented method in base class considered as "altering behavior"? Or, does the author mean altering method signatures and the output?

Also, I ready Duplicating code is not a good practice, and its a maintenance nightmare. Again, does overriding an already implemented method in base class considered "Duplicating code"? If not, what would be considered as "Duplicating code"? I

答:
I read somewhere that the chain of inheritance breaks when you alter a behavior from derived class. What does "altering a behavior" mean here?

Using C# as an example, you could have a base class such as :

```<code>public class SomeBaseClass
{
    public virtual void DoSomething()
    {
        Console.WriteLine("Hello world!");
    }
}
</code>```

And then a child class such as this:

```<code>public class MyChildClass : SomeBaseClass
{
    public override void DoSomething()
    {
        Console.WriteLine("This method now does something completely different!");
    }
}
</code>```

However, if you added base.DoSomething(); to the method MyChildClass, it would call both the parent method (outputting "Hello world!") and the new method (outputting "This method..."). The order they are displayed depends on where you put the base.DoSomething(); method call.

By avoiding calling the base method, I believe you would break the chain of inheritance, as it no longer performs the expected method of the parent class.

Another option is to use the new syntax on the method like so:

```<code>new public void DoSomething()
{
}
</code>```

This is called method hiding and lets you again define completely new behavior, but exposes a different method to the outside world, than the one that is visible by SomeBaseClass. I haven't had a need to use this myself, but I understand it can be helpful in some situations.

Of course, your milage may vary for these syntaxes and commands depending on the language of choice, but the general idea is the same.

I read that Duplicating code is not a good practice, and its a maintenance nightmare. Again, does overriding an already implemented method in base class considered "Duplicating code"?

Duplicating code is a bad practice, as it can lead to errors during maintenance. Suppose you had a function that calculates a value using some complex arithmetic or the like. Instead of properly creating a method for it, you just copy and paste it a dozen times as needed. Now, when something changes (and it will! Oh, things will change) you have to locate it a dozen times, and put the correct code in a dozen times. By putting it in a method you just change it once, and everything that uses that code is corrected as well.

Abstraction and inheritance reduce code duplication, because you can make a base class or method as a template, and you only have to write it once. Smart object design allows you to make highly-reuseable code which is proven to be tested and error-free. Plus, following inheritance guidelines will allow for child classes that can use code under the assumption that it "just works", and it can override the implementation, providing new or more specific behavior for itself as needed.

Body:
I read somewhere that the chain of inheritance breaks when you alter a behavior from derived class. What does "altering a behavior" mean here?

Using C# as an example, you could have a base class such as :

public class SomeBaseClass
{
    public virtual void DoSomething()
    {
        Console.WriteLine("Hello world!");
    }
}

And then a child class such as this:

public class MyChildClass : SomeBaseClass
{
    public override void DoSomething()
    {
        Console.WriteLine("This method now does something completely different!");
    }
}

However, if you added base.DoSomething(); to the method MyChildClass, it would call both the parent method (outputting "Hello world!") and the new method (outputting "This method..."). The order they are displayed depends on where you put the base.DoSomething(); method call.

By avoiding calling the base method, I believe you would break the chain of inheritance, as it no longer performs the expected method of the parent class.

Another option is to use the new syntax on the method like so:

new public void DoSomething()
{
}

This is called method hiding and lets you again define completely new behavior, but exposes a different method to the outside world, than the one that is visible by SomeBaseClass. I haven't had a need to use this myself, but I understand it can be helpful in some situations.

Of course, your milage may vary for these syntaxes and commands depending on the language of choice, but the general idea is the same.

I read that Duplicating code is not a good practice, and its a maintenance nightmare. Again, does overriding an already implemented method in base class considered "Duplicating code"?

Duplicating code is a bad practice, as it can lead to errors during maintenance. Suppose you had a function that calculates a value using some complex arithmetic or the like. Instead of properly creating a method for it, you just copy and paste it a dozen times as needed. Now, when something changes (and it will! Oh, things will change) you have to locate it a dozen times, and put the correct code in a dozen times. By putting it in a method you just change it once, and everything that uses that code is corrected as well.

Abstraction and inheritance reduce code duplication, because you can make a base class or method as a template, and you only have to write it once. Smart object design allows you to make highly-reuseable code which is proven to be tested and error-free. Plus, following inheritance guidelines will allow for child classes that can use code under the assumption that it "just works", and it can override the implementation, providing new or more specific behavior for itself as needed.


问:
Do markup languages have the equivalent concept of `semantics` that you can find in C or C++?
Maybe I miss something, but do the so called markup languages have the equivalent concept of semantics that you can find in C or C++?

Judging from how you parse the language, you don't really have too many options, there isn't too much context, you just parse your tokens and apply them to the source code.

I'm tempted to say that not only semantics doesn't exist in this case, but this only happens in markup languages: am I right?

答:
Markup languages most definitely have syntax (specific sequences of characters that defines tokens) and semantics (meaning to be applied to parsed content).  You can't really have a language without both.  You might possibly be able to argue about XML (semantics are really specific to a particular format, making each a DSL), but you can’t possibly argue about HTML.

What HTML lacks is EXPRESSION STATEMENTS or variables.  Without adding in CSS there's no way to make it do a calculation by itself.  This means it's not able to perform any calculations and is limited to giving semantics to content -- it can neither create or modify content on it's own.

Note that the way you typically add/modify html content on the fly is only possible because html has semantics -- in particular, you can say: this bunch of text is a computer program in language x, run it (where X is generally javascript).

ContentLicense: CC BY-SA 3.0


问:
How is quality important to the programmer, the person?
I didn't ask how the quality of the software is important to the product itself, the customers/users, the manager or the company. I want to know how it is important to the programmer that build it.

I'll be interested in any books (please specify the chapter), articles, blog post, and of course your personal opinion on the subject regardless your experience.

答:
I like to write quality software, simply because it helps me being more efficient: when code is well designed, I find it easier to add new features to the program and to maintain it.  So, quality code means quality programming time.

On top of that, being the most efficient possible is a nice intellectual challenge!

ContentLicense: CC BY-SA 2.5


问:
Identify this programming style
Some of the legacy code I've inherited uses the fact that C# supports multiple assignment to write code like:

```<code>void DisableControls()
{
    ddlStore.Enabled                =
    ddlProgram.Enabled              =
    ddlCat.Enabled                  =
    btnSaveProxy.Enabled            =
    btnCancelProxy.Enabled          =
    btnViewMassManagerProxy.Enabled =
    grdPromo.Enabled                = false;
}
</code>```

It's a very pretty style, with all the = lined up neatly, and the value being assigned down at the bottom, but it's also a rather annoying one to work with.  (And yes, those are tabs lining things up, not spaces).

I would like to know what, if anything, this style implies about the original coder,  since I've only seen it on a few occasions before.  Does it indicate a C++ background?  .NET 1.1?  Just someone's personal preference?

Is there any reason that the chained assignment like this would be more efficient than individually setting each control's .Enabled?  Less so? (This part was answered by @gnat's comment: This way makes it easy to insert btnWhatever.Enabled = as new buttons are added and delete as some buttons are deleted)

Edit: Other elements of this person's style, assuming the whole file was written by one person (likely but not certain), include putting function arguments on the next line, and putting commas at the beginning of a line instead of the end of the previous line.  Example:

```<code>PromoUpdate[] GetPromoUpdates(
                            StateField field)
{
    List<PromoUpdate> updates   = new List<PromoUpdate>();
    foreach (PromoOptInState p in field.States.Where(
                                                    x => x.IsDirty))
    {
        updates.Add(new PromoUpdate() {
            promoCode   = p.Code
            , optIn     = p.IsOptedIn
        });
    }
    return updates.ToArray();
}
</code>```

It's very weird.

答:
Putting commas at the beginning of a line rather than at the end of the previous one is common in SQL, so perhaps a database background?

It helps you comment out sections you don't want more easily, even if it is the last item in the list you are commenting out.

```<code>SELECT Name
       , Address
       -- , Email
FROM Customers
WHERE Address IS NOT NULL
  -- AND Email IS NOT NULL
</code>```

(Note the commented out lines pertaining to Email)

Yes, you could argue that commenting out the first line in the list now has an inconsistency, but that seems to be less of an issue.

Title: Identify this programming style

Body:
Putting commas at the beginning of a line rather than at the end of the previous one is common in SQL, so perhaps a database background?

It helps you comment out sections you don't want more easily, even if it is the last item in the list you are commenting out.

SELECT Name
       , Address
       -- , Email
FROM Customers
WHERE Address IS NOT NULL
  -- AND Email IS NOT NULL

(Note the commented out lines pertaining to Email)

Yes, you could argue that commenting out the first line in the list now has an inconsistency, but that seems to be less of an issue.


问:
ASP.NET deployment/maintenance best practices
I have been in the web development industry for around 5 years now, always working in an open source environment. Mostly apache, mysql, and php with a little bit of ruby, using git for version control. But recently took up a job where development is entirely C# ASP.NET MVC.

While I was able to pick up the language etc fairly easily, the other members of my team (with a lot more MS Development experience than me) all have a different way of thinking when it comes to publishing and deployment of the final site, and particularly future changes.

The mentality with the other developers is that once a site has been published it is final. No more changes can be made to the site, when I have asked the reasons behind this, the answers have been it is too dangerous, time consuming or difficult.

From my past experience, updating a site is simply a case of uploading the changed files, which is usually quite quick if it was a little change, or putting the site in maintenance mode while the update occurs.

We recently published an MVC Site, and the business contacted us to update some of the text and add a link to a new pdf document. The rest of my team were quick to say that this should not be done because the site is now live and should not be modified. Is there something I have missed by not being 'brought up' a Microsoft developer?

What are the argument against making modifications to a live web application in production and is this mindset unique to .NET developers?

I genuinely would like to understand this mindset and whether it is justified in a Microsoft development environment, or if this is just an older way of thinking.

NOTE: We use TFS for version control and use publish profiles to determine where the site gets deployed (UAT or Production)

答:
The main reason for the behavior you are seeing is that these types of changes are error prone. Manually updating the application leads to things being forgotten and getting out of sync. You should still be able to do new releases (and it should be easy), just not partial patches.

Partial updates like changing some CSS or text on a live site could lead to skipping testing, test or stage environments becoming out of sync, or even, not committing code to source control. If this is a code change, you could even end up breaking the live site with no recovery plan.

In .NET because code is compiled, there can be other problems such as long load times and loss of user sessions. These issues could be mitigated my swapping to a warm environment and using out of process session state. However, unless you want to think about these type of issues and other issues specific to your application every time you want to do a deployment. Then patching live websites is a bad idea.

As your application grows in size and people come and go this can move from an inconvenience to a serious issue. So to make things safer we follow rules like: To update a live website, it must be a complete deployment, never just patched.

If you're not automating your deployments yet (which make it easy and fast to follow the rule). New deployments are usually done next to the existing version and then your website is just a pointer to the version you want (Note database schema makes this a bit more complex).

```<code>1.0.0  // Old version you can roll back to
2.0.0 <-- IIS points here
</code>```

In reality, I think that all deployments should really be automated and that includes non .NET deployments as well, for similar reasons. Once you start automating deployments you can guarantee they're consistently fast and reliable.

Body:
The main reason for the behavior you are seeing is that these types of changes are error prone. Manually updating the application leads to things being forgotten and getting out of sync. You should still be able to do new releases (and it should be easy), just not partial patches.

Partial updates like changing some CSS or text on a live site could lead to skipping testing, test or stage environments becoming out of sync, or even, not committing code to source control. If this is a code change, you could even end up breaking the live site with no recovery plan.

In .NET because code is compiled, there can be other problems such as long load times and loss of user sessions. These issues could be mitigated my swapping to a warm environment and using out of process session state. However, unless you want to think about these type of issues and other issues specific to your application every time you want to do a deployment. Then patching live websites is a bad idea.

As your application grows in size and people come and go this can move from an inconvenience to a serious issue. So to make things safer we follow rules like: To update a live website, it must be a complete deployment, never just patched.

If you're not automating your deployments yet (which make it easy and fast to follow the rule). New deployments are usually done next to the existing version and then your website is just a pointer to the version you want (Note database schema makes this a bit more complex).

1.0.0  // Old version you can roll back to
2.0.0 <-- IIS points here

In reality, I think that all deployments should really be automated and that includes non .NET deployments as well, for similar reasons. Once you start automating deployments you can guarantee they're consistently fast and reliable.


答:
Common markup languages and common programming languages are indistinguishable in that they have both syntax and semantics. They differ only in that the purpose of a programming language is to generate executable code for a processor, while the purpose of a markup language is to generate declarative data for a display engine.

Both have a lexical structure. They are made up of tokens like words and numbers and punctuation.

Both have a syntactical structure. The tokens can be arranged in many different ways, and some arrangements are valid while others are not.

Both have a semantic structure. The tokens have meaning, some being predefined and some user-defined, and the way that tokens are arranged has meaning.

If we take the following code fragment:

```<code><div class="yolo">Hello world</div>
</code>```

The tokens div, class and the angle brackets have pre-defined meanings. The token "yolo" is a string which provides a user-defined name for the div. The angle brackets separate the markup from the text. These are semantic observations.

For both, the parser phase of the compiler stops at the same point, when it has generated a suitable internal representation  (such as an AST).

The next phase for a programming language is to generate code. The next phase for a markup language could be to generate a DOM. That phase is dependent on the the semantics, but not part of it.

Title: Do markup languages have the equivalent concept of `semantics` that you can find in C or C++?

Body:
Maybe I miss something, but do the so called markup languages have the equivalent concept of semantics that you can find in C or C++?

Judging from how you parse the language, you don't really have too many options, there isn't too much context, you just parse your tokens and apply them to the source code.

I'm tempted to say that not only semantics doesn't exist in this case, but this only happens in markup languages: am I right?

Body:
Common markup languages and common programming languages are indistinguishable in that they have both syntax and semantics. They differ only in that the purpose of a programming language is to generate executable code for a processor, while the purpose of a markup language is to generate declarative data for a display engine.

Both have a lexical structure. They are made up of tokens like words and numbers and punctuation.

Both have a syntactical structure. The tokens can be arranged in many different ways, and some arrangements are valid while others are not.

Both have a semantic structure. The tokens have meaning, some being predefined and some user-defined, and the way that tokens are arranged has meaning.

If we take the following code fragment:

<div class="yolo">Hello world</div>

The tokens div, class and the angle brackets have pre-defined meanings. The token "yolo" is a string which provides a user-defined name for the div. The angle brackets separate the markup from the text. These are semantic observations.

For both, the parser phase of the compiler stops at the same point, when it has generated a suitable internal representation  (such as an AST).

The next phase for a programming language is to generate code. The next phase for a markup language could be to generate a DOM. That phase is dependent on the the semantics, but not part of it.


问:
Looping Exhaustive Test Cases - A Good Practice?
Sometimes we have code like this:

```<code>private static final List<Goat> INEDIBLE_GOATS = [GOAT_A, GOAT_B, GOAT_C]

void eatGoat(Goat goat) {
   if(INEDIBLE_GOATS.contains(goat)) {
       throw new CantEatGoatException();
   }
   ...
}
</code>```

Should it best tested (along with whatever tests for the actual eating) as:

```<code>for(Goat goat: INEDIBLE_GOATS) {
   // forgive abuse of syntax
   assertThrows(CantEatGoatException, eatGoat(goat));
}
</code>```

Or more like?

```<code>assertThrows(CantEatGoatException, eatGoat(GOAT_A));
</code>```

Should tests verify each and every sort of inedible goat? Or should they test a representative goat from the list and trust that it works for the other goats?

答:
A major reason to have tests is to build your confidence in your code. Tested code can be proved to have a specific functionality because the tests say they do. Confidence grows from the proof. The question is, by looping through all the INEDIBLE_GOATS, do you gain any more confidence in your code? Either way, with both positive and negative tests, you cover the relevant code. With the loop, though, you are basically exercising these lines over and over. Essentially, you are testing that List<Goat>#contains() does what it says. Do you gain anything from that? If you trust that a List works as it should, then no, you don't get anything additional. If, on the other hand, you are not confident that a List works as it should, then you should have a separate test of List#contains() to give you that confidence.

You also have to balance the number of tests with the performance of your test suite. Looping through all the INEDIBLE_GOATS may give you a little more confidence, but if there are, say, 1.8 million of them, and running the tests takes 30 seconds longer, does that tiny additional confidence outweigh the lost time (and ensuing lost productivity).?

Finally, while INEDIBLE_GOATS may only have a small number of elements now, theoretically, the number of inedible Goats may actually be infinite. It is impossible to test every potential Goat. While in this simplified example, you may say that there won't really be infinite Goats, in general, we must account for infinite and near-infinite possible inputs and accept that we cannot practically test everything. We must also realize that this is a good thing. Not all inputs are equal, and trying to test everything wouldn't necessarily get us any more confidence. It is optimizing tests for confidence that makes them practical and profitable.


答:
I regularly republish / redeploy quite a few ASP.NET MVC websites deployed to Amazon AWS, Windows Azure and private webservers and don't see any reasons why your team makes such a big deal of it.

However, you should design you websites in such a way so that tasks like updating texts and links should be done through the database via the website admin interface.

My point is that while changes to a live website are OK (it's called development), redeploying the application to change a text string is likely indicative of a bad design. I am not suggesting the republishing could be done without care.

Title: ASP.NET deployment/maintenance best practices

Body:
I have been in the web development industry for around 5 years now, always working in an open source environment. Mostly apache, mysql, and php with a little bit of ruby, using git for version control. But recently took up a job where development is entirely C# ASP.NET MVC.

While I was able to pick up the language etc fairly easily, the other members of my team (with a lot more MS Development experience than me) all have a different way of thinking when it comes to publishing and deployment of the final site, and particularly future changes.

The mentality with the other developers is that once a site has been published it is final. No more changes can be made to the site, when I have asked the reasons behind this, the answers have been it is too dangerous, time consuming or difficult.

From my past experience, updating a site is simply a case of uploading the changed files, which is usually quite quick if it was a little change, or putting the site in maintenance mode while the update occurs.

We recently published an MVC Site, and the business contacted us to update some of the text and add a link to a new pdf document. The rest of my team were quick to say that this should not be done because the site is now live and should not be modified. Is there something I have missed by not being 'brought up' a Microsoft developer?

What are the argument against making modifications to a live web application in production and is this mindset unique to .NET developers?

I genuinely would like to understand this mindset and whether it is justified in a Microsoft development environment, or if this is just an older way of thinking.

NOTE: We use TFS for version control and use publish profiles to determine where the site gets deployed (UAT or Production)


问:
Overriding GetHashCode in a mutable struct - What NOT to do?
I am using the XNA Framework to make a learning project. It has a Point struct which exposes an X and Y value; for the purpose of optimization, it breaks the rules for proper struct design, since its a mutable struct.

As Marc Gravell, John Skeet, and Eric Lippert point out in their respective posts about GetHashCode() (which Point overrides), this is a rather bad thing, since if an object's values change while its contained in a hashmap (ie, LINQ queries), it can become "lost".

However, I am making my own Point3D struct, following the design of Point as a guideline. Thus, it too is a mutable struct which overrides GetHashCode(). The only difference is that mine exposes and int for X, Y, and Z values, but is fundamentally the same. The signatures are below:

```<code>public struct Point3D : IEquatable<Point3D>
{
    public int X;
    public int Y;
    public int Z;

    public static bool operator !=(Point3D a, Point3D b) { }
    public static bool operator ==(Point3D a, Point3D b) { }

    public Point3D Zero { get; }

    public override int GetHashCode() { }
    public override bool Equals(object obj) { }
    public bool Equals(Point3D other) { }
    public override string ToString() { }
}
</code>```

I have tried to break my struct in the way they describe, namely by storing it in a List<Point3D>, as well as changing the value via a method using ref, but I did not encounter they behavior they warn about (maybe a pointer might allow me to break it?).

Am I being too cautious in my approach, or should I be okay to use it as is?

答:
I see no particular problem in writing a struct like this, once you fully understand the trade-offs. The problem is (presumably) that you want to be to able to store it in a Dict (or similar collection) and you need a HashCode.

One thing you didn't mention is: do your points have identity? That is, if you have two points with the same value, are they the same point? [As two Integers both with the value 7 are the same integer. There is only one Integer with the value 7.]

Mutability implies identity. If a Point3D has identity then its HashCode is derived from its identity. You could use a this pointer or something like a GUID.

If the Point3D has no identity then its HashCode is best derived from its value. If you change the value (say by reusing values from a pool), you better make sure it's not in a Dict-like collection at the time or it will be lost.

Obviously if you don't use hash-based collections then the point is moot.

If you do, consider this code.

```<code>public struct ValuePoint {
  public int x;
  public int y;
  public override int GetHashCode() { return (x * 1000 + y) % 97; }
  public ValuePoint(int _x, int _y) { x = _x; y = _y; }
}
public struct IdentityPoint {
  static int nextkey = 0;
  int key;
  public int x;
  public int y;
  public override int GetHashCode() { return key; }
  public IdentityPoint(int _x, int _y) { key = ++nextkey; x = _x; y = _y; }
}
class Program {
  Dictionary<ValuePoint, int> dictv = new Dictionary<ValuePoint,int>();
  Dictionary<IdentityPoint, int> dicti = new Dictionary<IdentityPoint,int>();
  HashSet<ValuePoint> setv = new HashSet<ValuePoint>();
  HashSet<IdentityPoint> seti = new HashSet<IdentityPoint>();

  void exec() {
    ValuePoint vp = new ValuePoint(3, 4);
    dictv[vp] = 777;
    vp.x++;
    dictv[vp] = 888;
    IdentityPoint ip = new IdentityPoint(3, 4);
    dicti[ip] = 777;
    ip.x++;
    dicti[ip] = 888;
  }
</code>```

ValuePoint uses its value as its hashkey. If you change the value (x++) then the original value is 'lost', and the assigned value '888' adds a new key instead of updating the existing one.

IdentityPoint uses a unique key. If you change the value (x++) then the original entry is still found and overwritten with the assigned value '888'.

This is a contrived example, but illustrates the point about value versus identity. [The code is bad but good enough for the purpose.]

@EricLippert is a highly regarded writer whom I remember from the early days of COM and the design of .NET and his advice is sound. I think he misses the point by using a dictionary in which the key is a string. The issue of GetHashCode() only arises when the mutable object itself is the key.

Body:
I see no particular problem in writing a struct like this, once you fully understand the trade-offs. The problem is (presumably) that you want to be to able to store it in a Dict (or similar collection) and you need a HashCode.

One thing you didn't mention is: do your points have identity? That is, if you have two points with the same value, are they the same point? [As two Integers both with the value 7 are the same integer. There is only one Integer with the value 7.]

Mutability implies identity. If a Point3D has identity then its HashCode is derived from its identity. You could use a this pointer or something like a GUID.

If the Point3D has no identity then its HashCode is best derived from its value. If you change the value (say by reusing values from a pool), you better make sure it's not in a Dict-like collection at the time or it will be lost.

Obviously if you don't use hash-based collections then the point is moot.

If you do, consider this code.

public struct ValuePoint {
  public int x;
  public int y;
  public override int GetHashCode() { return (x * 1000 + y) % 97; }
  public ValuePoint(int _x, int _y) { x = _x; y = _y; }
}
public struct IdentityPoint {
  static int nextkey = 0;
  int key;
  public int x;
  public int y;
  public override int GetHashCode() { return key; }
  public IdentityPoint(int _x, int _y) { key = ++nextkey; x = _x; y = _y; }
}
class Program {
  Dictionary<ValuePoint, int> dictv = new Dictionary<ValuePoint,int>();
  Dictionary<IdentityPoint, int> dicti = new Dictionary<IdentityPoint,int>();
  HashSet<ValuePoint> setv = new HashSet<ValuePoint>();
  HashSet<IdentityPoint> seti = new HashSet<IdentityPoint>();

  void exec() {
    ValuePoint vp = new ValuePoint(3, 4);
    dictv[vp] = 777;
    vp.x++;
    dictv[vp] = 888;
    IdentityPoint ip = new IdentityPoint(3, 4);
    dicti[ip] = 777;
    ip.x++;
    dicti[ip] = 888;
  }

ValuePoint uses its value as its hashkey. If you change the value (x++) then the original value is 'lost', and the assigned value '888' adds a new key instead of updating the existing one.

IdentityPoint uses a unique key. If you change the value (x++) then the original entry is still found and overwritten with the assigned value '888'.

This is a contrived example, but illustrates the point about value versus identity. [The code is bad but good enough for the purpose.]

@EricLippert is a highly regarded writer whom I remember from the early days of COM and the design of .NET and his advice is sound. I think he misses the point by using a dictionary in which the key is a string. The issue of GetHashCode() only arises when the mutable object itself is the key.


问:
Drawbacks to redefining method in precompiled header
I have a lot of calls to NSLog(...). I need to change all of these calls to CLSNSLog(...).

So I added this to my precompiled header (.pch):

```<code>#import <CrashlyticsFramework/Crashlytics.h>
#define NSLog(...) CLSNSLog(__VA_ARGS__);
</code>```

Everything works. I don't see any drawbacks to this -- the team can continue to use NSLog(...) and I can revert pretty easily.

But am I missing anything, or are there any design issues this will create later on?

答:
The only issue I can see is that it may be confusing. NSLog is a commonly used function provided by Foundation framework. But you change it globally to something else and new developer may not aware of it.

Other than that, it should be fine since the header/define won't change often.


问:
What should plugins use: hooks, events or something else?
Consider an app that allows plugins to react to its program flow.

I know 2 ways to achieve this: hooks and events

1. Hooks

Use calls to empty functions inside the main program flow. These functions can be overriden by plugins.

For example, Drupal CMS implements hooks which are available to modules and themes. Here's an example of how hook is implemented in a file_copy function.

```<code>function file_copy(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
    // ... [File copying routine]

    // Inform modules that the file has been copied.
    module_invoke_all('file_copy', $file, $source);

    return $file;
    // ...
}
</code>```

A module can implement a modulename_file_copy($file, $source) function which will be called by the module_invoke_all in file_copy. After this function finishes, the file_copy will resume execution.

2. Events

Have the app dispatch events, which can be listened to by the plugins. After receiving an event that it's been subscribed to, a plugin will intercept the program flow and perform neccessary operations.

For example, a jQuery gallery plugin Fotorama implements several events. As an example, here's a part of its show method that fires the fotorama:show event.

```<code>  that.show = function (options) {
    // ... [show the new frame]

    // [fire the event]
    options.reset || triggerEvent('show', {
      user: options.user,
      time: time
    });

    // ... [do lots of other stuff with navigation bars, etc.]
  };
</code>```

A script can listen to this event and do something when it fires:

```<code>$('.fotorama').on(
  'fotorama:show',
  function (e, fotorama, extra) {
    console.log(e.type + (extra.user ? ' after user’s touch' : ''));
    console.log('transition duration: ' + extra.time);
  }
);
</code>```

QUESTION

Are there other mainstream ways to implement such plugin behaviour?

If not, when should one use hooks, and when should one use events? Considering the ultimate goal is to make the code more maintanable and readable, from both the app and the plugin developer's perspective?

答:
Definitely events. It allows your architecture be more wide-scalable.

Imagine what will happen if you'll need to place your plugin to a separate machine for example. Using events - you'll need just to modify a small peace of code to make your events network based.


答:
My grandfather designed river dams to last for centuries.  For something to hold up for any decent amount of time, it has to be good: even software.

My non-programming work (most of my work, actually) is similar: we have to keep referring to what we've studied and written, often on short notice, years later, under pressure (frequently, preparing for depositions or trials).  It has to be done well, the first time, or it is often not worth doing.

Title: How is quality important to the programmer, the person?

Body:
I didn't ask how the quality of the software is important to the product itself, the customers/users, the manager or the company. I want to know how it is important to the programmer that build it.

I'll be interested in any books (please specify the chapter), articles, blog post, and of course your personal opinion on the subject regardless your experience.


问:
static set and non-static get method
I've the following Interface.

```<code>public interface ValueInterface
{
  long  getValue();
}
</code>```

And the class:

```<code>public class ValueCreator implements ValueInterface
{
  private static long value  = 0;

  public void setValue(long valueInDollar)
  {
    value= valueInDollar;
  }

  @Override
  public long getValue()
  {
    return value;
  }
}
</code>```

The static code analyzer findbugs warned me not to set a static field in a non-static method. If I make the set method static, I can't make the getter static as it is an interface overridden method.

So, is it okay to have a static setter and non-static getter or what could be a better approach?

答:
FindBugs does not actually find bugs (or at least not only bugs). It finds things that are strange.
So if what you really want is have that value static and need to implement interface that gets value and it should return that value, you cannot do differently than non static method accessing static field.
If setter is not required by that interface, you can use static or non-static setter, it's up to you. But non-static method working with static data is something strange (not wrong), so i'd prefare static setter.

Are you sure that you want/need that value to be static? (but that's for different discussion)

Title: static set and non-static get method


答:
No, it is not a good idea to have a non-static getter for a static field.

The problem is that you can have multiple instances of ValieCreator, but they will all share the same static value field, so all instances will always return the same value and if you change the value through one instance, the modification is visible in all.

This is compounded by the fact that the getter is declared in the ValueInterface interface.
Suppose you have this code:

```<code>void SillyMethod(ValueInterface i, ValueCreator c)
{
    if (i != c)
    {  // different objects
        long val = i.getValue();
        c.setValue(val+1);
        if (val != i.getValue())
        {
            // Huh? Setter on c changed the value on a different object?
        }
    }
}
</code>```

It is  better to make the value field non-static. If you must ensure there can only ever be one ValueCreator, then you can use the Singleton pattern for that (but first ensure that there is no scenario imaginable where there might be two or more ValueCreator objects).

Title: static set and non-static get method

Body:
I've the following Interface.

```<code>public interface ValueInterface
{
  long  getValue();
}
</code>```

And the class:

```<code>public class ValueCreator implements ValueInterface
{
  private static long value  = 0;

  public void setValue(long valueInDollar)
  {
    value= valueInDollar;
  }

  @Override
  public long getValue()
  {
    return value;
  }
}
</code>```

The static code analyzer findbugs warned me not to set a static field in a non-static method. If I make the set method static, I can't make the getter static as it is an interface overridden method.

So, is it okay to have a static setter and non-static getter or what could be a better approach?

Body:
No, it is not a good idea to have a non-static getter for a static field.

The problem is that you can have multiple instances of ValieCreator, but they will all share the same static value field, so all instances will always return the same value and if you change the value through one instance, the modification is visible in all.

This is compounded by the fact that the getter is declared in the ValueInterface interface.
Suppose you have this code:

void SillyMethod(ValueInterface i, ValueCreator c)
{
    if (i != c)
    {  // different objects
        long val = i.getValue();
        c.setValue(val+1);
        if (val != i.getValue())
        {
            // Huh? Setter on c changed the value on a different object?
        }
    }
}

It is  better to make the value field non-static. If you must ensure there can only ever be one ValueCreator, then you can use the Singleton pattern for that (but first ensure that there is no scenario imaginable where there might be two or more ValueCreator objects).


问:
Are null references really a bad thing?
I've heard it said that the inclusion of null references in programming languages is the "billion dollar mistake".  But why?  Sure, they can cause NullReferenceExceptions, but so what?  Any element of the language can be a source of errors if used improperly.

And what's the alternative?  I suppose instead of saying this:

Customer c = Customer.GetByLastName("Goodman"); // returns null if not found
if (c != null)
{
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
```

<p>You could say this:</p>

<pre class="lang-cs prettyprint-override"><code>if (Customer.ExistsWithLastName("Goodman"))
{
    Customer c = Customer.GetByLastName("Goodman") // throws error if not found
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
</code>```

But how is that better?  Either way, if you forget to check that the customer exists, you get an exception.

I suppose that a CustomerNotFoundException is a bit easier to debug than a NullReferenceException by virtue of being more descriptive.  Is that all there is to it?

答:
Yes, NULL is a terrible design, in object-oriented world. In a nutshell, NULL usage leads to:

ad-hoc error handling (instead of exceptions)

ambiguous semantic

slow instead of fast failing

computer thinking vs. object thinking

mutable and incomplete objects

Check this blog post for a detailed explanation: http://www.yegor256.com/2014/05/13/why-null-is-bad.html

Title: Are null references really a bad thing?


问:
Is it better to return NULL or empty values from functions/methods where the return value is not present?
I am looking for a recommendation here.  I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined.

Take the following two methods as an examples:

string ReverseString(string stringToReverse) // takes a string and reverses it.
Person FindPerson(int personID)    // finds a Person with a matching personID.
```

In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that.  Also, this way, the caller would not have to check to see if a NULL was returned.

In FindPerson(), returning NULL seems like a better fit.  Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()).  So why not just return NULL here and then the caller only has to check for NULL.

Does anyone else struggle with this?  Any help or insight is appreciated.

答:
Returning NULL is a terrible design, in object-oriented world. In a nutshell, NULL usage leads to:

ad-hoc error handling (instead of exceptions)

ambiguous semantic

slow instead of fast failing

computer thinking vs. object thinking

mutable and incomplete objects

Check this blog post for a detailed explanation: http://www.yegor256.com/2014/05/13/why-null-is-bad.html


答:
Quality in my terms means the following: usability (less bugs, more features); simplicity;

I'm able to make the quality higher - this means I'm a good developer. I'm able to get paid higher, it is easy to find a good job.

Finally, I'm paid (bonuses) for high-quality software I produce.


问:
Should you throw an exception if a method's input values are out of range?
Should you throw an exception if a method's input values are out of range? eg

```<code>//no imaginary numbers
public int MySquareRoot(int x)
{
    if (x<0)
    {
    throw new ArgumentOutOfBoundsException("Must be a non-negative integer");
    }

    //our implementation here

}
</code>```

Now this method should never be called with a non-negative number, but hey programmers make mistakes. Is throwing exceptions here the right thing to do?

答:
Yes, I believe you should throw an exception, to help your fellow programmers notice the error at compile-time, by also adding throws ArgumentOutOfBoundsException in your method declaration.

That is, unless you use imaginary numbers in your project, where -1 is a perfectly valid argument for your square root method. :)


问:
From a DDD perspective is a report generating service a domain service or an infrastructure service?
Let assume we have the following service whose responsibility is to generate Excel reports:

```<code>class ExcelReportService{

   public String generateReport(String fileFormatFilePath, ResultSet data){
      ReportFormat reportFormat = new ReportFormat(fileFormatFilePath);
      ExcelDataFormatterService excelDataFormatterService = new ExcelDataFormatterService();
      FormattedData formattedData = excelDataFormatterService.format(data);
      ExcelFileService excelFileService = new ExcelFileService();
      String reportPath= excelFileService.generateReport(reportFormat,formattedData);
      return reportPath;
   }
}
</code>```

This is pseudo code for the service I want to design where:

fileFormatFilePath: path to a configuration file where I'll keep
the format of my excel file (headers, column widths, number of
columns,..etc)

data: the actual records returned from the database. This data

can't be used directly coz I might need to make further calculations
to the data before inserting them to the excel file.

ReportFormat: Value object to hold the report format, has methods

like getHeaders(), getColumnWidth(),...etc.

ExcelDataFormatterService: a service to hold any logic that need to
be applied to the data returned from the database before inserting it
to the file.

FormattedData: Value object the represents the formatted data to be
inserted.    ExcelFileService: a wrapper top the 3rd party library
that generates the excel file.

Now how do you determine whether a service is an infrastructure or domain service?

I have the following 3 services here:

ExcelReportService, ExcelDataFormatterService and ExcelFileService?

答: All of it is infrastructure service. Domain in DDD is primarily concerned with data and business rules that operate on this data. It has nothing to do with how the data are presented. So in your example, the only part that would be related to domain is how you get the data.


答:
You should do something, as this answer says, exceptions are helpful, it's good to fail-fast etc etc. In fact I would add that they help at read time, I would say they document the intended input better than the top comment in your example.

However there are alternatives. If I've surmised your languages correctly: Debug.Assert(x > 0) and Contract.Requires( x > 0 );

However, the consensus seems to be that using exceptions in a release build is the best approach.

Asserts seem to be intended for debugging and it's more useful to ship with exceptions and that Contracts aren't quite there yet and neither is good for public methods. It's non-trivial, and doesn't lend itself to quick summary. I suggest reading that page.

Overall, I would tend to favour exceptions, but asserts may be a decent choice as well for internal methods.

Body:
Should you throw an exception if a method's input values are out of range? eg

```<code>//no imaginary numbers
public int MySquareRoot(int x)
{
    if (x<0)
    {
    throw new ArgumentOutOfBoundsException("Must be a non-negative integer");
    }

    //our implementation here

}
</code>```

Now this method should never be called with a non-negative number, but hey programmers make mistakes. Is throwing exceptions here the right thing to do?


问:
What to translate in a billingual software
I'm designing/building a web application that will be available in two languages: French/English. I placed i18n mechanisms to extract every text from the application. But what about the user's input?

I have some "system settings" that currently ask for both lang for their labels...

But I can't obviously ask a translation for every input (pure data, receipts, etc)...

Where can you trace the line between what should be available in translations?

N.B : An instance of the application (a same database) will be used by more than one person (~10 users).

答:
As a non-native English speaker, I always have to develop my projects with the option to translate at a later time, as it seems very very wrong to build anything with a default language other than English. So, I have tried various approaches and I believe it really depends on your project input.

Scenario 1

An online application for managing clients won't need any translation on input, as clients' names are obviously non-translatable contents. Users from both languages should be comfortable seeing the client data in the client's native language.

Scenario 2

An application to build an input form / input template (which may eventually be part of the UI). Your users may have to create fields, etc, for other users - in which case translating is necessary. Depending on how you implement your translation, you may ask them to:

Write both languages

Write an alias that will be used by someone who is responsible for translating the UI

Write only one language and give the ability to other users to translate.

To elaborate on 3, you can show your (e.g.) English text to French users, if a translation is not available, but give them the ability to translate it on the fly, with a Translate this! link or something.

To summarize, I don't believe anyone can help you draw a clear line on what to translate or how, without knowing more about your project. In my opinion, it is good practice to pass every part of the UI through translation when coding, so that you can decide what to translate later on, by editing the database or whichever method you use for translating.

Body:
As a non-native English speaker, I always have to develop my projects with the option to translate at a later time, as it seems very very wrong to build anything with a default language other than English. So, I have tried various approaches and I believe it really depends on your project input.

Scenario 1

An online application for managing clients won't need any translation on input, as clients' names are obviously non-translatable contents. Users from both languages should be comfortable seeing the client data in the client's native language.

Scenario 2

An application to build an input form / input template (which may eventually be part of the UI). Your users may have to create fields, etc, for other users - in which case translating is necessary. Depending on how you implement your translation, you may ask them to:

Write both languages

Write an alias that will be used by someone who is responsible for translating the UI

Write only one language and give the ability to other users to translate.

To elaborate on 3, you can show your (e.g.) English text to French users, if a translation is not available, but give them the ability to translate it on the fly, with a <sup>Translate this!</sup> link or something.

To summarize, I don't believe anyone can help you draw a clear line on what to translate or how, without knowing more about your project. In my opinion, it is good practice to pass every part of the UI through translation when coding, so that you can decide what to translate later on, by editing the database or whichever method you use for translating.


问:
Pure Front end JavaScript with Web API versus MVC views with ajax
This was more a discussion for what peoples thoughts are these days on how to split a web application.

I am used to creating an MVC application with all its views and controllers. I would normally create a full view and pass this back to the browser on a full page request, unless there were specific areas that I did not want to populate straight away and would then use DOM page load events to call the server to load other areas using AJAX.

Also, when it came to partial page refreshing, I would call an MVC action method which would return the HTML fragment which I could then use to populate parts of the page. This would be for areas that I did not want to slow down initial page load, or areas that fitted better with AJAX calls. One example would be for table paging. If you want to move on to the next page, I would prefer it if an AJAX call got that info rather than using a full page refresh. But the AJAX call would still return an HTML fragment.

My question is. Are my thoughts on this archaic because I come from a .net background rather than a pure front end background?

An intelligent front end developer that I work with, prefers to do more or less nothing in the MVC views, and would rather do everything on the front end. Right down to web API calls populating the page. So that rather than calling an MVC action method, which returns HTML, he would prefer to return a standard object and use javascript to create all the elements of the page.

The front end developer way means that any benefits that I normally get with MVC model validation, including client side validation, would be gone. It also means that any benefits that I get with creating the views, with strongly typed html templates etc would be gone.

I believe this would mean I would need to write the same validation for front end and back end validation. The javascript would also need to have lots of methods for creating all the different parts of the DOM. For example, when adding a new row to a table, I would normally use the MVC partial view for creating the row, and then return this as part of the AJAX call, which then gets injected into the table. By using a pure front end way, the javascript would would take in an object (for, say, a product) for the row from the api call, and then create a row from that object. Creating each individual part of the table row.

The website in question will have lots of different areas, from administration, forms, product searching etc. A website that I don't think requires to be architected in a single page application way.

What are everyone's thoughts on this?

I am interested to hear from front end devs and back end devs.

答:
I'll offer my highly subjective 2 penny worth (for what it's worth ;)). There isn't a right or wrong answer to this and there are many real world considerations in addition to your points, for example:

Do you have the relevant experience in house? building a client side driven app is very different to a predominantly server driven one with a completely different skill set.

How long do you want it to take and which browsers do you need to support? - the more you do on the client the more browser issues you'll face; IE8 is painful and JavaScript performance is quite poor, but there there are a lot of businesses running XP/IE set ups.

What devices are your users going to be viewing the site on? JavaScript parsing and running may be fast on a recent version of Chrome - but it isn't on an older mobile device, especially not a large amount of JavaScript with a load of business logic in it

How important is initial load? Server templating is faster than client templating

This list is by no means exhaustive and sounds like a client side bashing which isn't my intention, I've made sites with a heavy emphasis on the front end end.

For me it really comes down to user experience and API re-usability. To address each of these.

If you are going to be making an app or offering an API, there's a lot of sense in using a .Net API project, this then forms the logic, checking and implementation cross platform. In this scenario a complete client side approach may be favourable, the API can be maintained separately and just provides an interface to your application. You can amend the logic and refactor comfortably and just have to keep the interface the same. You can easily write different applications for different media all using the same background code.

The strongest argument for a pure front end solution (in my opinion) is that of user experience.

Does (when considering all the downsides) a pure JavaScript browser application offer a substantial improvement on usability and user experience on a traditional website?

When creating sites that work like native applications; I'd argue the answer is an obvious yes. Most sites however aren't this clean cut though, so it's a matter of assessing whether individual user workflows benefit from a highly dynamic interface.

I take a fairly pragmatic view of this, it isn't an either or matter; JavaScript will obviously play quite happily along with Server technologies and you don't have to choose one or the other - every site isn't a single page web app - but there's nothing stopping you using Knockout, backbone and the suchlike on individual pages to improve things where it's deemed necessary.


问:
Helping someone who is not and never will be a professional programmer write code that is more legible and usable to use and interpret
I am Elvis, trying very hard to learn to be Einstein. I work for Mort.

What the hell is this crazy idiot talking about!?!? (You only need to read the first few paragraphs)

If you don't feel like reading that link, basically, I am a professional programmer, and my boss is (this is scarily accurate):

the professional line-of-business programmer who lacks a degree in computer science but has a great deal of familiarity with Office and VBA, and who typically writes productivity applications shared amongst his coworkers

All that said, a large portion of my job is taking his cobbled together code and making it production ready. However, the very poor style and cargo-cultism makes this difficult. This is compounded by the fact that he is unwilling to read programming books or allow me to help him refactor his code.

Are there some other strategies for helping someone who is not a professional programmer, never will be a professional programmer write code going forward that is more legible and usable for me to use and interpret?

答:
I'm not sure I will add something to this discussion, but having worked in similar scenarios where an Access violation is hitting at a line with ShowMessage('Hello'); or similar, only to find out that the same line has more code, out of the screen to the right,

I believe that you have two basic options:

Let the code run. If the code is working and doing what it should do, unless your boss is specifically asking you to fix their code, just leave it as it is. That may also lead him to understand that your code looks nicer and leave the work to you (as also pointed by Dunk in his answer).

If you are very determined to make the code professional, build a library / framework that he can use. If there is a pattern on the errors / strategies that you commonly fix, you may be able to wrap those up into a few library files and give it to him as a "base library for the company", which you can also use as a common interface.

ContentLicense: CC BY-SA 4.0


问:
Front end developers vs HTML/CSS coders plus "the JavaScript developer"
I was just googling around to find a good definition of front-end developer and the definitions that I found were pretty much "a guy that does HTML/CSS/JavaScript (jQuery)".

But I think this is no longer the case. Today we have very complex interfaces, say a single page BackboneJS app that require a lot more than just "a guy that does HTML/CSS/JavaScript" and has no background in Computer Science.

I would argue that the guy that engineers the front-end app (Backbone, Angular, etc) should be as (if not more) skilled  programmer than the guy that engineers the back-end.

So in my scenario (single page webapp - say with Backbone), I have 3 people:

A back-end programmer - the guy responsible for all the API calls that the Backbone app would make

A "front-end" programmer - they guy that's responsible for getting the work from the designer (wireframes if you will) and turning it into responsive, cross-browser, cross-platform HTML/CSS code

The "JavaScript" developer who makes everything light up, hooks up the HTML/CSS to the API and brings the app to life.

My question is: What is the most usual modern dev team structure? How is the work usually divided between the front end and back end developers.

Of course if you only have full-stack developers that can produce JavaScript and say PHP equally well, then you have less of an issue. But still, who is the front-end developer and how do you call "the JavaScript developer"?

Excuse my simple language, I tried to stay as far away from terminology as possible.

答:
I  agree it sounds like you do have a 'modern' dev team structure. Much like the last few I have been a part of.

I think inefficiencies can arise from defining responsibilities or 'domains' as intrinsic properties of the team though, it smells too much like a collection of jobs rather than a team of engineers adding the most value they can towards achieving a common goal.

I think full stack familiarity is essential, so everyone fluently speaks the same language - describing problems and solutions precisely (end to end if appropriate) builds confidence in the direction of the project, and accelerates discussion of the hard problems.  It also creates an 'us', an 'our thing' for each team member to get behind and own. If just one guy is 'the UI' you have a doorway to concepts like blame and martyrdom creeping in to the dynamic.

Conversely, shared ownership and skills, combined with having true expertise in specialised areas creates a fertile ecosystem where each member is inspired by their teammates, and has the empowering experience of building a fulfilling contribution, in which they 'led' the whole team, inspiring I turn.

Above all,  my opinion is there should be a recurring focus on the user, and the design of an ''experience' which transparently 'just works'

Honesty and trust in your team's abilities can't be manufactured,  however a culture with a pervasive appreciation of real customer service is what I've seen work before, to great effect.


问:
Why do we have to use divs?
This morning, as I was writing some html and haml, it occurred to me that the way divs are used is ridiculous.
Why are divs not implied? Imagine if this:

```<code><div class="hero-img">
   <img src="http://whatever.com/this.jpg">
</div>
</code>```

was this:

```<code><hero-img>
   <img src="http://whatever.com/this.jpg">
</hero-img>
</code>```

If the "div class" portion of the element was assumed, HTML would be more semantic, and infinitely more readable with the matching closing tags!

This is similar to HAML, where we have:

```<code>.content Hello, World!
</code>```

Which becomes:

```<code><div class='content'>Hello, World!</div>
</code>```

It seems to me the only thing that would have to happen for this to work in browsers is that the browsers could start interpreting every element without an existing html element definition as implying <div class="<element name>">.

This could be completely backward compatible; for CSS and jQuery selectors etc, "div.hero-img" could still work, and be the required syntax to select the elements.

I know about the new web components specification, but that is significantly more complicated than what is suggested here. Can you imagine how pleasant it would be to look at a website's source and see html that looked like that?!

So why do we have to use divs?

If you look at Mozilla's html5 element list, every element has a semantic meaning, and then we get to
 and it says:

"Represents a generic container with no special meaning."

..and then they list the arbitrary elements they are adding to html5 like .

Of course, if this concept of implied divs was added to the html spec, it would take ten years to become standard, which is a million years in web time.

So I figure there must be a good reason this hasn't happened yet. Please, explain it to me!

答:
Problem 1: White-spaces

I believe that this hasn't come up in general. Although, one good reason that this hasn't and probably shouldn't happen is because white-spaces in CSS classes define multiple classes for the element, while in HTML they define attributes.

Explain (or ask a browser to parse) the following code:

```<code><pet family style=" ... ">
  <img src="my-pets-family.jpg"/>
</pet family>
</code>```

Is family the definition of a second class or an attribute to the HTML element? As you probably see from this site's parser, it thinks it's an attribute.

So, if I want
, there is no way to actually define two classes, which is one of the two main reasons that I would use a class instead of an id, anyway.

Problem 2: Forward compatibility!

Using
s at the moment, forces us (at least some of us) to properly indent and comment around our code, which is a good practice for all programming languages.

Instead, turning HTML blocks into variables would cause big confusion to new programmers as to what is and what isn't doing something specific in HTML.

Also, it will cause the funny side-effect that you should start comparing your old code against new HTML5 tags, just to make sure that they didn't come up with the same name you did for your div's classes...

Same problem applies to variables using reserved words in some languages. PHP solved it with a dollar-sign, so a similar approach in HTML would result into something not much better than the current usage of
.

Title: Why do we have to use divs?

Body:
Problem 1: White-spaces

I believe that this hasn't come up in general. Although, one good reason that this hasn't and probably shouldn't happen is because white-spaces in CSS classes define multiple classes for the element, while in HTML they define attributes.

Explain (or ask a browser to parse) the following code:

<pet family style=" ... ">
  <img src="my-pets-family.jpg"/>
</pet family>

Is family the definition of a second class or an attribute to the HTML element? As you probably see from this site's parser, it thinks it's an attribute.

So, if I want <div class="pet family">, there is no way to actually define two classes, which is one of the two main reasons that I would use a class instead of an id, anyway.

Problem 2: Forward compatibility!

Using <div>s at the moment, forces us (at least some of us) to properly indent and comment around our code, which is a good practice for all programming languages.

Instead, turning HTML blocks into variables would cause big confusion to new programmers as to what is and what isn't doing something specific in HTML.

Also, it will cause the funny side-effect that you should start comparing your old code against new HTML5 tags, just to make sure that they didn't come up with the same name you did for your div's classes...

Same problem applies to variables using reserved words in some languages. PHP solved it with a dollar-sign, so a similar approach in HTML would result into something not much better than the current usage of <div class="something">.


答:
Your own example displays one property why divs are not that ridiculous.

```<code><div class="hero-img">
  <img src="http://whatever.com/this.jpg">
</div>
</code>```

You have, correctly, not closed the img tag. Some tags, such as img, br, hr, and others do not have any content, and are therefore not to be closed. The parser knows this.

The div tag, on the other hand, is supposed to be closed, as it contains content.
If you just whipped up you own tag, the parser would have no idea if it should expect the tag to be closed or not.

The reason why some elements are to be closed and others are not comes from the SGML heritage, which this blog post describes nicely:
http://www.colorglare.com/2014/02/03/to-close-or-not-to-close.html

Title: Why do we have to use divs?

Body:
This morning, as I was writing some html and haml, it occurred to me that the way divs are used is ridiculous.
Why are divs not implied? Imagine if this:

```<code><div class="hero-img">
   <img src="http://whatever.com/this.jpg">
</div>
</code>```

was this:

```<code><hero-img>
   <img src="http://whatever.com/this.jpg">
</hero-img>
</code>```

If the "div class" portion of the element was assumed, HTML would be more semantic, and infinitely more readable with the matching closing tags!

This is similar to HAML, where we have:

```<code>.content Hello, World!
</code>```

Which becomes:

```<code><div class='content'>Hello, World!</div>
</code>```

It seems to me the only thing that would have to happen for this to work in browsers is that the browsers could start interpreting every element without an existing html element definition as implying <div class="<element name>">.

This could be completely backward compatible; for CSS and jQuery selectors etc, "div.hero-img" could still work, and be the required syntax to select the elements.

I know about the new web components specification, but that is significantly more complicated than what is suggested here. Can you imagine how pleasant it would be to look at a website's source and see html that looked like that?!

So why do we have to use divs?

If you look at Mozilla's html5 element list, every element has a semantic meaning, and then we get to
 and it says:

"Represents a generic container with no special meaning."

..and then they list the arbitrary elements they are adding to html5 like .

Of course, if this concept of implied divs was added to the html spec, it would take ten years to become standard, which is a million years in web time.

So I figure there must be a good reason this hasn't happened yet. Please, explain it to me!

Body:
Your own example displays one property why divs are not that ridiculous.

<div class="hero-img">
  <img src="http://whatever.com/this.jpg">
</div>

You have, correctly, not closed the img tag. Some tags, such as img, br, hr, and others do not have any content, and are therefore not to be closed. The parser knows this.

The div tag, on the other hand, is supposed to be closed, as it contains content.
If you just whipped up you own tag, the parser would have no idea if it should expect the tag to be closed or not.

The reason why some elements are to be closed and others are not comes from the SGML heritage, which this blog post describes nicely:
http://www.colorglare.com/2014/02/03/to-close-or-not-to-close.html


答:
I'd like to add another reason why throwing an exception is the best choice here: Unit-testing and TDD.

Every mature testing framework should be capable of asserting that a certain method throws when giving a certain input. By writing a unit test that checks for such an exception, you can document valid and invalid input for the method while at the same time validating that invalid input will indeed get rejected.

This is much harder when you're using assertions instead (or some other mechanism).

Title: Should you throw an exception if a method's input values are out of range?


问:
Storing session in a static variable?
I'm currently checking a older piece of C# code used to maintain a login session.

```<code>public static ZRWebserviceSession CurrentSession { get { return _currSession; } set { _currSession = value; } }
private static ZRWebserviceSession _currSession;

public static bool IsSessionActive()
{
    if (_currentSession == null || !_currentSession.IsOpen || !_currentSession.IsLoggedIn) {
         return false;
    }
    return true;
}
</code>```

I was always told using globals is bad practice and I'm looking for ways to improve this bit of code by at least getting rid of the static field used to maintain the session.

The current situation is as follows:

When the application starts the session object is initiated with a server address (taken from a config file) it should connect to. The object then retrieves the session data (token etc.) from the server to store within itself and it is then assigned to the static variable for access through the entire application. This is only done at the start of the application run or when the user explicitly restarts the session.

While a session is active other pieces of code can then call methods on the session object to retrieve the session data and make calls to the connected webservice.

Can this be improved? Is using globals still a bad practice if used for sessions or something akin to that?

EDIT: To clarify what kind of application this is: This isn't a web application but a client application that connects to a webservice. ZRWebserviceSession is a library object that represents a login session for the user currently using the client application. Kind of like the the session object of the Fabebook SDK https://developers.facebook.com/docs/reference/ios/current/class/FBSession/.

答:
Never store sessions in a static variable!

Static variable means that when another user logs in, the static variable will be updated it with the new session and the first user will work under the last user's session. Never user static varible in a web application.

The only case where i use static variables is with constants(which are static by default);

Update:

Well a good use of static variable with session could be that when the user logs in, save the user object in session and then do this:

```<code>    var user = GetUser('username','password');

    if(user == null){
      throw new NullReferenceException("user does not exists! login failed");
   }

    else{
    Session["currentuser"] = user;

    }
</code>```

So now you can do this:

```<code>public class Globals{

  public static User GetCurrentUser()
  {
     return (User)System.Web.HttpSessionStateBase["currentuser"];
  }
}
</code>```

So that when you need the current user information you just call Globals.GetCurrentUser().

Title: Storing session in a static variable?

Body:
Never store sessions in a static variable!

Static variable means that when another user logs in, the static variable will be updated it with the new session and the first user will work under the last user's session. Never user static varible in a web application.

The only case where i use static variables is with constants(which are static by default);

Update:

Well a good use of static variable with session could be that when the user logs in, save the user object in session and then do this:

    var user = GetUser('username','password');

    if(user == null){
      throw new NullReferenceException("user does not exists! login failed");
   }

    else{
    Session["currentuser"] = user;

    }

So now you can do this:

public class Globals{

  public static User GetCurrentUser()
  {
     return (User)System.Web.HttpSessionStateBase["currentuser"];
  }
}

So that when you need the current user information you just call Globals.GetCurrentUser().


答:
The purpose of a div element is structure alone. It lets you group elements together under one common element. It has nothing to do with white space, speed, rendering, semantics or anything else. It helps you with CSS in terms of styling and javascript in terms of selectors. If you change it to any other element then you change the purpose.

To create your own named element, as you show, has a problem in that search engines and other tools would not know what your elements meaning had. What is a "hero-img" and how is it different from my "hero-image" and how should my API handle that when I visit your page? How should a browser handle that element? Is it block level or inline? Too many questions.

Title: Why do we have to use divs?


问:
How is quality important to the programmer, the person?
I didn't ask how the quality of the software is important to the product itself, the customers/users, the manager or the company. I want to know how it is important to the programmer that build it.

I'll be interested in any books (please specify the chapter), articles, blog post, and of course your personal opinion on the subject regardless your experience.

答:
If your question mean that "Should quality be important to programmer as a professional", the answer is, "Unequivocally yes".

However if your question is "do programmers care about quality personally", answer is, "It depends".

On the one hand there are programmers who are not satisfied until they have perfected the code, but on the other hand there are programmers whose main interest is problem solving, once they have the solution, quality seems like irksome details to them.

If you fall in the latter kind (as I do, I am not proud to admit), you must try to fight and overcome this tendency. Of course sometimes perfect can be enemy of good too.

Update: Now why are some programmers perfectionists and other analytical. I believe the answer to that lies in psychology and genetics. Investigating that is both outside the limit of this answer and my knowledge as well. That said, I will note following

Although these are not necessarily mutually exclusive, really good programmers are more comfortable with problem solving than quality, as I believe programming at its core is about problem solving.

doesn't however mean that if you are good at problem solving you are necessarily a good programmer. To use mathematical terms problem solving is a "necessary" condition whereas aspiring for quality is a "sufficient" one.


答:
If you can code your method or its signature in such a way that the exception condition cannot happen, doing so is arguably the best approach.

For example, with the particular example you bring up, does your language have an unsigned integer data type with an appropriate range? If so, just use that one rather than a corresponding signed integer type and throwing an exception for any value passed in that is less than 0. In that case, a negative value cannot be used in that position in a well-formed program; the compiler will catch the mistake long before runtime, and at the very least issue a warning (for signed/unsigned type use mismatch), unless you go out of your way to explicitly bypass that safety net; and if you're forcing a signed variable into a function whose method signature says unsigned integer only without making sure that the value is within an acceptable range for that function, then I'd argue that the programmer doing so deserves to get an exception thrown in their face.

As another example, if only a reasonably small set of values is valid as input, maybe those can be expressed as an enumeration with a specific set of values rather than using a plain integer value to encode each possible value? Even if under the hood the enum collapses to an int, using enumerations protects from programmer mistakes.

If you cannot write the method signature in such a way that the exception condition cannot possibly happen in a well-formed program, then I would argue that this is exactly what ArgumentOutOfRangeException, IllegalArgumentException and similar exception types are intended for. This can also trivially be worked into a TDD workflow. Just make sure to make it clear what the error is; particularly if you don't have easy access to the source code, getting a non-specific ArgumentOutOfRangeException thrown back at you can be greatly frustrating. Note the documentation for these exception types:

ArgumentOutOfRangeException (.NET): "The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method." (as seen here)

IllegalArgumentException (Java): "Thrown to indicate that a method has been passed an illegal or inappropriate argument." (as seen here)

Writing the method to make the exception condition impossible to begin with will help even more than throwing an exception at runtime, but we must acknowledge that sometimes this is just not possible in practice. You'll still need to check invariants not directly related to the range of a single parameter value at runtime, though; for example, if x + y > 20 is an error, but x and y each can be anything <= 20, I don't think there's an easy way to express that in the method signature.


问:
In what situation do Entity Framework enums become useful?
I am working on a project where there will be plenty of static options being stored in the database. I looked at using Enums for this, but do not see how they could be useful.

They do not create any kind of look-up table, just reference a number in the table which can be used in code as an enum option. The number is meaningless to anyone creating SSRS reports and if you need to add an extra option, you need to recompile.

Is there a situation where these have a genuine purpose and are a better fit than an entity. Or are they generally a bad practice for the above reasons?

答:
Using a number to represent an enum value is slightly more efficient in terms of database lookup.  The downside is of course that it is ghastly difficult to understand what anything is.

This is a matter of opinion, however I believe emphasis should be placed on readability, also in the database.  As such, I would prefer readable string values in the database. However, you lose the advantage of using enums in your code, hence I would suggest to convert from enums to strings and vice versa.  Use the enum name as it is used in your code and if it is minimally descriptive, you should easily be able to understand what type you're dealing with by looking at the database.

You could also take this a step further and insert the full formal name of the enum type in order to recreate it using reflection, but I would avoid this technique if possible.

Also be sure that these values are really truly static in nature.  Adding one or two extra enum types is no big deal, but more than that and you're likely dealing with a dynamic value and at that point it should have its own database table.


问:
Fixing bugs generated by another team
I'm facing the following situation:

There are 2 different teams working on the same project using Scrum, and every now and then, bugs related to user stories developed by team "A" are being assigned to team "B".  We're used to fixing bugs made by other people when they belong to the same team, but things get a bit more complicated when different teams are involved. Some of the developers don't like working this way and say that the bugs must be fixed by the ones who made them, and this is causing some conflicts between the teams.

While reading some of the similar questions I've found some interesting ones (Is fixing bugs made by other people a good approach? and also Parallel teams and scrum/agile), but they are not about the same situation, or at least I don't see them that way.

During our discussions here we got 2 possible approaches: Leave the situation as is, or determine that the bugs must be assigned to the team that developed the feature. Do you guys have any suggestions?

答:
I see it as an opportunity to casually code review the bug location and its surroundings, so I have never been too bothered when this happened to me.

Perhaps this could be used as a third possibility; treat the bugs as code review time, or peer debugging time. This lets you also gain an idea of the business side the other team is working with; since one team seems to be depending on the other it is always useful to share this knowledge.

Ideally this would need to evolve organically, letting the most painful problems emerge from discussion; I strongly think that this should not be mandated by management :)

Title: Fixing bugs generated by another team


答:
If I call a function, I expect it to do something. If it cannot do what I requested, I should be notified -- the function shouldn't do nothing or do something wrong.

I can be notified by it returning a specific return value (e.g. a floating point sqrt function could return NaN for a bad number), setting an external error variable, or throwing an exception. (The first or third are preferred.)

In your case, your function can't do what is requested of it when x is less than zero. Throwing an exception saying the argument is out of range is perfectly acceptable and nicely informative.


答:
bugs must be fixed by the ones who made them

Programmers looking for some sort of right and wrong in the world and not finding justice-Where's Batman when you need him! No point in upsetting people for without a reason, so let's see if there are some over-all 'company' benefits.

Team Work Load - at times one team will get busier than another. This happens because of members leaving or taking time off. They may have less talent. It is possible their part is just harder.

Accountability - This needs to be considered from a team level. Are they being lazy and creating bugs because they can just leave it to the other guy. I wouldn't assume this is happening. One day, they may have to fix your bugs.

Inefficient Use of Time - It takes longer to fix unfamiliar bugs. See #1 to determine whether or not one team can still do it faster than the other. Only if you can demonstrate that a disproportionate amount of time is spent fixing other team's bugs and in the long-run slows the entire project down, do you have a real argument.

It's just not fun. - It's true, but I wouldn't make this argument. You can state that it makes your team feel less important by being required to do more of this type of work.

Find out who has decided to do this any why. Then you can consider the pros and cons. Let them know it bothers you, but you have to compare the teams outrage to the benefits to the client and the client should win unless they are completely skewed. Sharing a scrum master between two teams could be the problem. A dedicated SM may be more territorial and protective because of the negative impact on the team.

Title: Fixing bugs generated by another team

Body:
I'm facing the following situation:

There are 2 different teams working on the same project using Scrum, and every now and then, bugs related to user stories developed by team "A" are being assigned to team "B".  We're used to fixing bugs made by other people when they belong to the same team, but things get a bit more complicated when different teams are involved. Some of the developers don't like working this way and say that the bugs must be fixed by the ones who made them, and this is causing some conflicts between the teams.

While reading some of the similar questions I've found some interesting ones (Is fixing bugs made by other people a good approach? and also Parallel teams and scrum/agile), but they are not about the same situation, or at least I don't see them that way.

During our discussions here we got 2 possible approaches: Leave the situation as is, or determine that the bugs must be assigned to the team that developed the feature. Do you guys have any suggestions?


答: With the other suggestions about it being a good chance for a code review.  Would it be feasible for the person who is assigned the bug to pair with someone from the other team to fix it.  The combination of people from each team will help to expand the knowledge of the code base as well as get a feel for how the other team works.</p>

Title: Fixing bugs generated by another team


问:
A license like the LGPL, but compatible with JavaScript
I have written a library that is quite extensive and has taken up a lot of my time, so I would like to license it properly. The LGPL seems to have many of the things I want, but does not work with Javascript or other interpreted languages.

Here are the things I want my license to say:

My library can be used in commercial application (either web or desktop applications).

My library can be used in open source applications (again, any platform is fine).

You may not redistribute my unmodified library in any form, except for when the javascript is downloaded to the client's browser.

I would like to remain as the copyright owner.

If possible, I would like users of my library to be able to use other libraries under any license (though this is less important).

I am fine with distributing source of my library, and I'll have to since it's JS, the thing I don't want is others distributing my unmodified library and saying it is purely their work. I am ok with people modifying and redistributing the library, though I would rather they submitted their work to me and I would give them credit. If they do modify and redistribute the library, they must give me partial credit.

I have also thought about using the MIT license, but it clearly states that people could redistribute my library unmodified, which is the most important thing to me, to make that impossible.

I sincerely apologize if an identical question has been asked on this network, I have done several days' research and have not found one (this is the closest I've gotten, but the answer didn't help me).

Also, IANAL so if any of this is legally contradictory or impossible, please explain rather than just stating that it is impossible.

答:
(Based on the 8th comment to the question)

If you want your name to remain on all copies and derivative versions, the BSD license is sufficient. BSD in fact requires exactly that, nothing less, nothing more.

The BSD license is compatible with all open-source licenses, and most commercial licenses.  (Where not compatible, it's the fault of that other license, so your 5th point is also addressed). However, your third point contradicts your second point, and it's rather pointless anyway. How would you enforce it indirectly? Modifications of modifications, in other words.


答:
I understand your question as "Should you validate input data?", as opposed to "Should you use Exceptions instead of error codes?".

When accepting input parameters from outside - be it a method with call-parameters, XML input data from a service call or a web-page with user-fields - you basically have two choices:

make rigorus checks whether the input data match the expected format

trust your caller to only call you with correct data

Adding checks adds complexity

the initial developer has to think of all valid (or "possibly invalid") values and add appropriate checks. Ideally this is done at the beginning of the method, though sometimes it has to be done later (e.g. if "valid input value" is "the ID of an actually existing object in the database")

further developers trying to understand the actual logic of the method, as it adds more lines to investigate.

runtime overhead to check all assumptions

On the other hand, input validation brings valuable benefits:

It enables you to make assumptions deeper down in the coding, as they are already verified

further developers may have more to read, but making assumptions about input data explicit also helps understanding the logic, and that corner cases are taken care of.

It ensures that no corrupt program states (crashes, data corruption, security vulnerabilities) can occur.

So the choice of adding checks should be done in context where your method is used.

Is it exposed to untrusted, external data, like web sites or public APIs? Then definitely do thorough validation.

is it a private method in an often-called inner-loop, protected by outer coding? Then you probably don't want redundant checks. You might want to document your expectations (e.g. JavaDoc), though that's rarely done in practice.

some languages provide conditionally compiled assertions, which are enabled in debug builds for catching program logic errors, but disabled for performance in productive use

for libraries you have to decide how much you trust your callers. Better err on the side of caution and add checks, especially if you don't want your library invariants to be compromised. For speed relevant functions, though, you could decide differently (and document it).

usually a mixture is done: good validation on externally facing methods, some validation on interface levels, very few (often just NullPointerChecks) in the inner workings of a program.

If your question however was "Are Exceptions the right way to signal invalid input data?", the answer is: most likely yes.

Exceptions impose quite an overhead on the runtime performance, but makes reasoning about the program flow drastically easier. This reduces faulty programming (semantic errors), especially as it forces you to deal with them - they 'fail securely' by terminating the program if they are ignored. They are ideal for 'situations which are not supposed to happen'. Also they can transport metadata like a stacktrace.

Error codes, on the other hand, are light-weight, fast, but forces the method caller to explicitely check them. Failure to do so often results in program flaws, which can range from silent data corruption, security holes, to nice fireworks if your program happens to be running inside a space rocket.

One example where I personally would have preferred error codes instead of exceptions is the String.parseInt() method in Java. Getting a non-digit string from an input source (e.g. a user) is not totally unexpected and I have to deal with it in any case - sometimes as simple as using a default value. As a caller, I have no way of checking the data whether it would provoce an exception (short of implementing the validator logic myself), thus generating the exception as part of normal program flow and using try-catch-blocks is the only choice here.

Please note that error codes could be both in-band and out-of-band:

In-band: a special (magic) value is declared to be a marker for the error condition. Often null or -1 is used here, e.g. in string-search-methods

Out-of-Band: a separate value is returned, indicating 'no error' (usually 0 or null) or the specific error. This can be done either as the / an additional return parameter (for languages supporting multiple return values - e.g. Googles GO supports this especially for errors) or as a requirement to call a special "getError()" method.