问:
Inheritance/OO design question
This will probably wind up being a fairly simple question, but it needs some background first... I'm modelling various hardware switches, which can be turned on and off. The switches are configurable, allowing a user to specify the numeric values that are sent to the hardware to signal that it should turn on or off. This is the Switch class:-

```<code>public class Switch
{
    public Id { get; set; }
    public SwitchConfig Config { get; set; }

    public void TurnOn()
    {
        WriteToSerialPort(Id, Config.OnValue);
    }

    public void TurnOff()
    {
        WriteToSerialPort(Id, Config.OffValue);
    }
}

public class SwitchConfig
{
    public int OnValue { get; set; }
    public int OffValue { get; set; }
}
</code>```

So far so good.

I now need to model a new type of switch that can not only be turned on and off, but can also have a temperature threshold set, so it seems sensible to inherit from the Switch class. The configuration will also need extending to include min/max permitted temperatures, e.g.:-

```<code>public TemperatureSwitchConfig : SwitchConfig
{
    public int MinTemperature { get; set; }
    public int MaxTemperature { get; set; }
}
</code>```

The specialised switch class will look something like this:-

```<code>public TemperatureSwitch : Switch
{
    public void SetTemperature(int temperature)
    {
        var temperatureSwitchConfig = Config as TemperatureSwitchConfig;

        if (temperature < temperatureSwitchConfig.MinTemperature
            || temperature > temperatureSwitchConfig.MaxTemperature)
        {
             return;
        }

        WriteToSerialPort(Id, temperature);
    }
}
</code>```

It doesn't feel "right" where I'm having to cast the Config property. I'm sure there must be a slicker OO solution to this, but I think "analysis paralysis" has set in and I can't see the wood for the trees! Or am I worrying over nothing - is the casting an acceptable solution in this scenario?

答:
Most OO languages properly implement the rules of subtyping, as stated by Barbara Liskov (in "A behavioral notion of subtyping", see fig. 4). In particular, if you have a method with the signature

```<code>X method(Y arg1, Z arg2);
</code>```

then you can override this method in a subclass using the signature

```<code>A method(B arg1, C arg2);
</code>```

where:

A is a subclass of X (or is X)

B is a superclass of Y (or is Y)

C is a superclass of Z (or is Z)

In your case, your TemperatureSwitch class could override

```<code>SwitchConfig Switch::Config();
</code>```

with

```<code>TemperatureSwitchConfig Switch::Config();
</code>```

Thus, if you have a variable of type TemperatureSwitch, its Config method will return you a TemperatureSwitchConfig. If you have a variable of type Switch that actually points to a TemperatureSwitch, then its Config method will return you a SwitchConfig, which is actually a TemperatureSwitchConfig (just like your current situation).

Title: Inheritance/OO design question

Body:
Most OO languages properly implement the rules of subtyping, as stated by Barbara Liskov (in "A behavioral notion of subtyping", see fig. 4). In particular, if you have a method with the signature

X method(Y arg1, Z arg2);

then you can override this method in a subclass using the signature

A method(B arg1, C arg2);

where:

A is a subclass of X (or is X)

B is a superclass of Y (or is Y)

C is a superclass of Z (or is Z)

In your case, your TemperatureSwitch class could override

SwitchConfig Switch::Config();

with

TemperatureSwitchConfig Switch::Config();

Thus, if you have a variable of type TemperatureSwitch, its Config method will return you a TemperatureSwitchConfig. If you have a variable of type Switch that actually points to a TemperatureSwitch, then its Config method will return you a SwitchConfig, which is actually a TemperatureSwitchConfig (just like your current situation).


答:
You can make the config a parameter:</p>

```<code>public abstract class Switch<TConfig> where TConfig : SwitchConfig
{
    public Id { get; set; }
    public TConfig { get; set; }

    public void TurnOn()
    {
        WriteToSerialPort(Id, Config.OnValue);
    }

    public void TurnOff()
    {
        WriteToSerialPort(Id, Config.OffValue);
    }
}

public class NormalSwitch : Switch<SwitchConfig>
{
}

public TemperatureSwitch : Switch<TemperatureSwitchConfig>
{
    public void SetTemperature(int temperature)
    {

        if (temperature < Config.MinTemperature
            || temperature > Config.MaxTemperature)
        {
             return;
        }

        WriteToSerialPort(Id, temperature);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Inheritance/OO design question

Body:
This will probably wind up being a fairly simple question, but it needs some background first... I'm modelling various hardware switches, which can be turned on and off. The switches are configurable, allowing a user to specify the numeric values that are sent to the hardware to signal that it should turn on or off. This is the Switch class:-

```<code>public class Switch
{
    public Id { get; set; }
    public SwitchConfig Config { get; set; }

    public void TurnOn()
    {
        WriteToSerialPort(Id, Config.OnValue);
    }

    public void TurnOff()
    {
        WriteToSerialPort(Id, Config.OffValue);
    }
}

public class SwitchConfig
{
    public int OnValue { get; set; }
    public int OffValue { get; set; }
}
</code>```

So far so good.

I now need to model a new type of switch that can not only be turned on and off, but can also have a temperature threshold set, so it seems sensible to inherit from the Switch class. The configuration will also need extending to include min/max permitted temperatures, e.g.:-

```<code>public TemperatureSwitchConfig : SwitchConfig
{
    public int MinTemperature { get; set; }
    public int MaxTemperature { get; set; }
}
</code>```

The specialised switch class will look something like this:-

```<code>public TemperatureSwitch : Switch
{
    public void SetTemperature(int temperature)
    {
        var temperatureSwitchConfig = Config as TemperatureSwitchConfig;

        if (temperature < temperatureSwitchConfig.MinTemperature
            || temperature > temperatureSwitchConfig.MaxTemperature)
        {
             return;
        }

        WriteToSerialPort(Id, temperature);
    }
}
</code>```

It doesn't feel "right" where I'm having to cast the Config property. I'm sure there must be a slicker OO solution to this, but I think "analysis paralysis" has set in and I can't see the wood for the trees! Or am I worrying over nothing - is the casting an acceptable solution in this scenario?

Body:
You can make the config a parameter:

public abstract class Switch<TConfig> where TConfig : SwitchConfig
{
    public Id { get; set; }
    public TConfig { get; set; }

    public void TurnOn()
    {
        WriteToSerialPort(Id, Config.OnValue);
    }

    public void TurnOff()
    {
        WriteToSerialPort(Id, Config.OffValue);
    }
}

public class NormalSwitch : Switch<SwitchConfig>
{
}

public TemperatureSwitch : Switch<TemperatureSwitchConfig>
{
    public void SetTemperature(int temperature)
    {

        if (temperature < Config.MinTemperature
            || temperature > Config.MaxTemperature)
        {
             return;
        }

        WriteToSerialPort(Id, temperature);
    }
}


答:
Your comment about needing to generate the Config from xml adds a whole new dimension to the problem.  Strong types are most helpful at compile time, which isn't applicable here.  My inclination would be to instead create a Dictionary to hold the parsed config, and use it like:

public TemperatureSwitch : Switch
{
    public void SetTemperature(int temperature)
    {
        if (temperature < config["MinTemperature"]
         || temperature > config["MaxTemperature"])
        {
             return;
        }

        WriteToSerialPort(Id, temperature);
    }
}
```

You can put validation into your parser code, or into the setter code.  Alternately, you could just forego the Config altogether, and have your xml parser code create the Switch objects directly, with individual fields for the config items.

Title: Inheritance/OO design question

Body:
Your comment about needing to generate the Config from xml adds a whole new dimension to the problem.  Strong types are most helpful at compile time, which isn't applicable here.  My inclination would be to instead create a Dictionary to hold the parsed config, and use it like:

public TemperatureSwitch : Switch
{
    public void SetTemperature(int temperature)
    {
        if (temperature < config["MinTemperature"]
         || temperature > config["MaxTemperature"])
        {
             return;
        }

        WriteToSerialPort(Id, temperature);
    }
}

You can put validation into your parser code, or into the setter code.  Alternately, you could just forego the Config altogether, and have your xml parser code create the Switch objects directly, with individual fields for the config items.


答:
Well, you can use the C# generics (or equivalent in your choice of language). so basically your 1st code block would look like:

```<code>    public class Switch<T> where T:SwhitchConfig
    {
       public Id { get; set; }
       public T Config { get; set; }

       public void TurnOn()
       {
           WriteToSerialPort(Id, Config.OnValue);
       }

       public void TurnOff()
       {
            WriteToSerialPort(Id, Config.OffValue);
       }
   }

   public class SwitchConfig
   {
       public int OnValue { get; set; }
       public int OffValue { get; set; }
   }
</code>```

And your specialized implementation would look like:

```<code>    public TemperatureSwitch : Switch<TemperatureSwitchConfig>
    {

    }
</code>```

Title: Inheritance/OO design question

Body:
Well, you can use the C# generics (or equivalent in your choice of language). so basically your 1st code block would look like:

    public class Switch<T> where T:SwhitchConfig
    {
       public Id { get; set; }
       public T Config { get; set; }

       public void TurnOn()
       {
           WriteToSerialPort(Id, Config.OnValue);
       }

       public void TurnOff()
       {
            WriteToSerialPort(Id, Config.OffValue);
       }
   }

   public class SwitchConfig
   {
       public int OnValue { get; set; }
       public int OffValue { get; set; }
   }

And your specialized implementation would look like:

    public TemperatureSwitch : Switch<TemperatureSwitchConfig>
    {

    }


答:
Disclaimer: My C# is pretty rusty. The syntax may be off.

I now need to model a new type of switch that can not only be turned on and off, but can also have a temperature threshold set, so it seems sensible to inherit from the Switch class.

A natural response, but you should be careful. Inheritance is dangerous, it shouldn't be your first reaction to a problem.

Here's my take on this:

First, since all your fields are public, it doesn't make sense to make TurnOn and TurnOff methods. It'd be slightly better to have these be static functions. The upside is that when you need to change the implementation of TurnOn/TurnOff or provide alternate implementations, you don't need to recompile anything that depends on Switch.

Next, you can easily make Switch immutable, and you should prefer immutability when possible. By making it immutable you don't have to worry about keeping track of possible state changes as you pass Switch values around in your program. It also allows you to use them as keys in dictionaries, since a key's equality and hashcode shouldn't depend on mutable state.

With that out of the way, we need to tackle the issue that there's more than one kind of switch. You need to make a decision here: do I want to make introducing new types of switches easy, or make it easy to do new things with the switches you already have? Given that these are hardware switches, it'd guess that the addition of new switch types will be a relatively rare event. If that's the case, you'd benefit from using a sum type. This will restrict us to a finite set of kinds of switches but give us a type-safe way to distinguish between them and ensure you appropriately handle each one. So, your code would go something like this (constructors omited for brevity):

```<code>// Switch.cs
public abstract Switch {
    private Switch() {} // Prevent inheritance outside of this scope

    public abstract R Match<R>(Func<NormalSwitch, R> IfNormal, Func<TemperatureSwitch, R> IfTemp);

    public sealed NormalSwitch : Switch {
        public <IdType> Id { get; }
        public SwitchConfig Config { get; }

        public R Match<R>(Func<NormalSwitch, R> IfNormal, Func<TemperatureSwitch, R> IfTemp); {
            return IfNormal(this);
        }
    }

    public sealed TemperatureSwitch : Switch {
        public <IdType> Id { get; }
        public TempSwitchConfig Config { get; }

        public R Match<R>(Func<NormalSwitch, R> IfNormal, Func<TemperatureSwitch, R> IfTemp); {
            return IfTemp(this);
        }
    }
}

// SwitchFunctions.cs
public static class SwitchFunctions {
    public static void TurnOn(NormalSwitch Switch) { ... }
    public static void TurnOff(NormalSwitch Switch) { ... }
}

// TempSwitchFunctions.cs
public static class TempSwitchFunctions {
    public static void TurnOn(TemperatureSwitch Switch) { ... }
    public static void TurnOff(TemperatureSwitch Switch) { ... }
    public static void SetTemperature(TemperatureSwitch Switch) { ... }
}
</code>```

Now in your client code you may do this:

```<code>Switch switch = parseXml()
switch.match(
    IfNormal: NormalSwitch => TurnOn(NormalSwitch),
    IfTemperature: TempSwitch => {
        TurnOn(TempSwitch);
        SetTemperature(TempSwitch);
    }
);
</code>```

It's all strongly-typed, and you can write alternative implementations to the switch functions without having to recompile anything that depends on the original implementations.

Uh oh, I introduced some functional programming into your code. But that's OK, since your Switch was just a data container.

Title: Inheritance/OO design question

Body:
Disclaimer: My C# is pretty rusty. The syntax may be off.

I now need to model a new type of switch that can not only be turned on and off, but can also have a temperature threshold set, so it seems sensible to inherit from the Switch class.

A natural response, but you should be careful. Inheritance is dangerous, it shouldn't be your first reaction to a problem.

Here's my take on this:

First, since all your fields are public, it doesn't make sense to make TurnOn and TurnOff methods. It'd be slightly better to have these be static functions. The upside is that when you need to change the implementation of TurnOn/TurnOff or provide alternate implementations, you don't need to recompile anything that depends on Switch.

Next, you can easily make Switch immutable, and you should prefer immutability when possible. By making it immutable you don't have to worry about keeping track of possible state changes as you pass Switch values around in your program. It also allows you to use them as keys in dictionaries, since a key's equality and hashcode shouldn't depend on mutable state.

With that out of the way, we need to tackle the issue that there's more than one kind of switch. You need to make a decision here: do I want to make introducing new types of switches easy, or make it easy to do new things with the switches you already have? Given that these are hardware switches, it'd guess that the addition of new switch types will be a relatively rare event. If that's the case, you'd benefit from using a sum type. This will restrict us to a finite set of kinds of switches but give us a type-safe way to distinguish between them and ensure you appropriately handle each one. So, your code would go something like this (constructors omited for brevity):

// Switch.cs
public abstract Switch {
    private Switch() {} // Prevent inheritance outside of this scope

    public abstract R Match<R>(Func<NormalSwitch, R> IfNormal, Func<TemperatureSwitch, R> IfTemp);

    public sealed NormalSwitch : Switch {
        public <IdType> Id { get; }
        public SwitchConfig Config { get; }

        public R Match<R>(Func<NormalSwitch, R> IfNormal, Func<TemperatureSwitch, R> IfTemp); {
            return IfNormal(this);
        }
    }

    public sealed TemperatureSwitch : Switch {
        public <IdType> Id { get; }
        public TempSwitchConfig Config { get; }

        public R Match<R>(Func<NormalSwitch, R> IfNormal, Func<TemperatureSwitch, R> IfTemp); {
            return IfTemp(this);
        }
    }
}

// SwitchFunctions.cs
public static class SwitchFunctions {
    public static void TurnOn(NormalSwitch Switch) { ... }
    public static void TurnOff(NormalSwitch Switch) { ... }
}

// TempSwitchFunctions.cs
public static class TempSwitchFunctions {
    public static void TurnOn(TemperatureSwitch Switch) { ... }
    public static void TurnOff(TemperatureSwitch Switch) { ... }
    public static void SetTemperature(TemperatureSwitch Switch) { ... }
}

Now in your client code you may do this:

Switch switch = parseXml()
switch.match(
    IfNormal: NormalSwitch => TurnOn(NormalSwitch),
    IfTemperature: TempSwitch => {
        TurnOn(TempSwitch);
        SetTemperature(TempSwitch);
    }
);

It's all strongly-typed, and you can write alternative implementations to the switch functions without having to recompile anything that depends on the original implementations.

Uh oh, I introduced some functional programming into your code. But that's OK, since your Switch was just a data container.


问:
How to test state of the object
I have a class DataImport
with only two public methods

```<code>public void fromStream(InputStream inputStream);
public ImportCommand getImportCommand();
</code>```

When I test it I send some test data to fromStream method

```<code>dataImport.fromStream(some stream with data...)
</code>```

Only way how to test the result of this method is to get the ImportCommand from getImportCommand and test if this object is in the state according to the input I provided.

But what if ImportCommand has only one method?

```<code>public ImportResult execute();
</code>```

I could test ImportResult (after invoking execute() which would involve some mocks and additional setup) because it has some state exposed. But this way I am testing ImportCommand and the DataImport class in one unit test which does not feel right to me.

But exposing inner state of the classes I am testing or accessing their private fields/methods also is not good thing.

Does this mean that my design is not ok (how should I change it) or is there some way how to solve this situation?

Related: TDD anti-patterns on SO

答:
Don't do any processing in the fromStream() method, just call another method - something like procesStreamResult() that get called whenever something comes in from the stream. This way, you can test procesStreamResult() by calling it with mock objects as arguments and also implement proper error handling and unit testing.

What I'm basically trying to say is: decouple the actual outside dependency (the stream, in your case) from the internal workings of your own code and only test the code you need to test.

Title: How to test state of the object


问:
Should I strictly follow every single HTML and CSS Standard?
A few years ago I considered myself somewhat of a web developer, knowing the basic 3 languages (HTML, CSS, JS) and lots of PHP. Moving on from simple text to actual websites was a pain because of the so called "standards" out there, which at the time were ridiculously complicated for me. It pretty much boiled down to this (minus the IE related stuff):

Standards are there to replace old ways of doing things in a simpler way. However when trying to actually implement some of the stuff (Entirely CSS based layout for example), it took me 10x longer to actually do it then if I did the simpler and still working solution. If it rendered the same, then why should I use the more complicated example that takes 10x longer and breaks once you change browsers? This sparked many long religious debates in ##php, ##css, and ##js in Freenode IRC and actually got me banned from ##css because I messed with their little world over there.

My question: Should I follow every single standard and coding conventions even if they take me 10x longer but get me the same result as the simple one?

For the poll tag, those of you who have websites of any size (huge or small), do you follow all the standards?

答:
I would say 'adhere' to standards as best as you can - but don't waste too much time nitpicking, sometimes you can over engineer a standard HTML/CSS in the pursuit of standards perfection and be left in the worst state.

As an example, in one of our web applications we have a page for invoicing. The page lists a long list of items to be invoiced and contains several columns. The original developer went so overboard with the "Tables are evil" syndrome he designed the whole 'table' structure in CSS.

Pretty impressive, until you are the one who now needs to add an extra few columns to the report, watch those columns go all over the place because you need to readjust the CSS settings, width etc..... nightmare.

If the developer wasn't so anal about following so called standards right down to the tee, he would of realised that actually, a regular html table would make soo much more sense, the invoice date is after all, tabular.

This leads me onto semantic HTML. I do believe that your HTML should only contain elements that describe your page. Styles should be stored in CSS and at the very worst, entered in the 'Style' attribute of the HTML tag where applicable.

I also see no valid reason why one should not put their HTML through a validator - provided you are getting valid HTML you are pretty much there.

ContentLicense: CC BY-SA 2.5


答:
I recommend you to remove Config property from the class and put all the properties of it into the class itself. Then, you set those properties in constructor of each switch or as properties.

You say that SwitchConfig comes from XML serialization. What if you want to parametrize that serialization in some way, this is usually done using attributes in model classes (SwitchConfig in your case). Then the SwitchConfing and transitively Switch becomes dependent on module for XML serialization.

What if you would want to create the switches based on something else than XML? Then you would need to needlessly create the Config classes, instead of setting the parameters in constructors or properties.

Last thing that comes to mind is: How do you create concrete type of Switch class? Eg. how do you decide to create Switch or TemperatureSwitch? Probably based on type of SwitchConfig. If you already have code like this, why not just make it into full-featured factory, that builds specific switches based on XML data? And the XML serialization can be encapsulated internally inside this factory.

And if you are worrying about having to change many things when configuration changes, then you can do what Karl Bielefeldt said and use weak-typed deserialization instead of explicit class model.

Title: Inheritance/OO design question


问:
Why do C# developers newline opening brackets?
I've spent most of the last several years working mainly with C# and SQL. Every programmer I've worked with over that time was in the habit of placing the opening brace of a function or control flow statement on a new line. So ...

```<code>public void MyFunction(string myArgument)
{
     //do stuff
}

if(myBoolean == true)
{
    //do something
}
else
{
    //do something else
}
</code>```

I have always been struck by how space wasteful this is, especially in if/else statements. And I know alternatives exist in later versions of C#, like:

```<code>if(myBoolean == true)
    //do something on one line of code
</code>```

But hardly anyone used them. Everyone did the curly-brace-on-newline thing.

Then I got back into doing JavaScript after a long absence. In my memory, JavaScript developers used to do the exact same curly-brace-newline thing but with all the fancy new libraries and stuff, most developers put the opening brace after the declaration:

```<code>function MyJavaScriptFunction() {
    //do something
}
</code>```

You can see the sense in this, because since using closures and function pointers has become popular in JavaScript, it saves a lot of space and makes things more readable. So I wondered why it wasn't seen as the done thing in C#. In fact, if you try the above construct in Visual Studio 2013, it actually reformats it for you, putting the opening brace on a new line!

Now, I just saw this question on Code Review SE:
https://codereview.stackexchange.com/questions/48035/questions-responses-let-me-tell-you-about-you
In which I learned that in Java, a language I'm not overly familiar with, it's considered de-rigour to open your curly braces right after the declaration, in modern JavaScript fashion.

I had always understood that C# was originally modelled after Java, and kept to a lot of the same basal coding standards. But in this instance, it seems not. So I presume there must be a good reason: what is the reason? Why do C# developers (and Visual Studio) enforce opening curly brackets on a new line?

答:
The convention that you associate with Java is the K&R style, or the "One true brace style," and originally comes from C. This page indent-style from the venerable Jargon File shows how old the distinction is.

I've always thought that the Allman style and its variants are a reflection of how the authors think about code, elevating the block delimiters to the level of keywords similar to how some languages use "begin" and "end" around blocks of code.


答:
The reason C# developers do it is because it is the default setting of the Visual Studio auto-formatter. While this setting can be changed, most people don’t, and thus all developers in a team have to go with the majority.

As for why this is the default in Visual Studio, I don’t know.

Title: Why do C# developers newline opening brackets?

Body:
I've spent most of the last several years working mainly with C# and SQL. Every programmer I've worked with over that time was in the habit of placing the opening brace of a function or control flow statement on a new line. So ...

```<code>public void MyFunction(string myArgument)
{
     //do stuff
}

if(myBoolean == true)
{
    //do something
}
else
{
    //do something else
}
</code>```

I have always been struck by how space wasteful this is, especially in if/else statements. And I know alternatives exist in later versions of C#, like:

```<code>if(myBoolean == true)
    //do something on one line of code
</code>```

But hardly anyone used them. Everyone did the curly-brace-on-newline thing.

Then I got back into doing JavaScript after a long absence. In my memory, JavaScript developers used to do the exact same curly-brace-newline thing but with all the fancy new libraries and stuff, most developers put the opening brace after the declaration:

```<code>function MyJavaScriptFunction() {
    //do something
}
</code>```

You can see the sense in this, because since using closures and function pointers has become popular in JavaScript, it saves a lot of space and makes things more readable. So I wondered why it wasn't seen as the done thing in C#. In fact, if you try the above construct in Visual Studio 2013, it actually reformats it for you, putting the opening brace on a new line!

Now, I just saw this question on Code Review SE:
https://codereview.stackexchange.com/questions/48035/questions-responses-let-me-tell-you-about-you
In which I learned that in Java, a language I'm not overly familiar with, it's considered de-rigour to open your curly braces right after the declaration, in modern JavaScript fashion.

I had always understood that C# was originally modelled after Java, and kept to a lot of the same basal coding standards. But in this instance, it seems not. So I presume there must be a good reason: what is the reason? Why do C# developers (and Visual Studio) enforce opening curly brackets on a new line?


答:
The brace at the end of the line is the ancient K&R C standard, from Brian Kernighan and Dennis Ritchie's book The C Programming Language, which they published in 1978 after co-inventing the UNIX operating system and the C programming language (C was mostly designed by Ritchie, based on B, which another Bell employee Ken Thompson had adapted from the older BCPL programming language), at AT&T.

There used to be flame wars about "the one true brace style."

So Ritchie created the C language, and Kernighan wrote the first tutorial, when computer displays only showed a few lines of text. In fact, UNICS (later UNIX) development started on a DEC PDP-7, which used a typewriter, printer and paper tape for a user interface. UNIX and C were finished on the PDP-11, with 24-line text terminals.  So vertical space was indeed at a premium.  We all have slightly better displays and higher resolution printers today, right? I mean, I don't know about you, but I have three 24" 1080p displays in front of me right now. :-)

Also, so much of that little book The C Programming Language is code samples that putting the braces at the ends of the lines instead of on their own lines allegedly saved an appreciable amount of money on printing.

What is truly important is consistency throughout a project, or at least within a given source code file.

There are also scientific studies showing that the brace on its own line (indented to the same level as the code, in fact) improves code comprehension despite what people think they think of the aesthetics. It makes it very clear to the reader, visually and instinctively, which code runs in which context.

```<code>if( true )
    {
    // do some stuff
    }
</code>```

C# has always supported evaluating a single command after a branching expression, by the way. In fact, that's the only thing it does, even now. Putting code in braces after a branching expression just makes that one command a goto (the compiler creates scope using jmp instructions). C++, Java, C# and JavaScript are all more or less based on C, with the same underlying parsing rules, for the most part. So in that sense, C# is not "based on Java."

Summing up, this is a bit of a religious/flame-war issue. But there are studies making it pretty clear that arranging code in blocks improves human comprehension. The compiler couldn't care less. But this is also related to the reason why I never put a line of code after a branch without braces--it's just too easy for me or another programmer to slap another line of code in there later and slip on the fact that it will not execute in the same context with the line right before or after it.

EDIT: Just go look at the Apple goto fail bug for a perfect example of this exact issue, which had very serious real world consequences.

```<code>if( true )
    doSomething();
</code>```

becomes...

```<code>if( true )
    doSomething();
    doSomethingElse();
</code>```

In this case, doSomethingElse() executes every time, regardless of the outcome of the test, but because it is indented to the same level as the doSomething() statement, it's easy to miss. This isn't really arguable; studies back this up. This is a big source of bugs introduced into source code during maintenance.

Still, I'll admit that JavaScript closure syntax looks a little silly with braces on their own lines...aesthetically. :-)

Body:
The brace at the end of the line is the ancient K&R C standard, from Brian Kernighan and Dennis Ritchie's book The C Programming Language, which they published in 1978 after co-inventing the UNIX operating system and the C programming language (C was mostly designed by Ritchie, based on B, which another Bell employee Ken Thompson had adapted from the older BCPL programming language), at AT&T.

There used to be flame wars about "the one true brace style."

So Ritchie created the C language, and Kernighan wrote the first tutorial, when computer displays only showed a few lines of text. In fact, UNICS (later UNIX) development started on a DEC PDP-7, which used a typewriter, printer and paper tape for a user interface. UNIX and C were finished on the PDP-11, with 24-line text terminals.  So vertical space was indeed at a premium.  We all have slightly better displays and higher resolution printers today, right? I mean, I don't know about you, but I have three 24" 1080p displays in front of me right now. :-)

Also, so much of that little book The C Programming Language is code samples that putting the braces at the ends of the lines instead of on their own lines allegedly saved an appreciable amount of money on printing.

What is truly important is consistency throughout a project, or at least within a given source code file.

There are also scientific studies showing that the brace on its own line (indented to the same level as the code, in fact) improves code comprehension despite what people think they think of the aesthetics. It makes it very clear to the reader, visually and instinctively, which code runs in which context.

if( true )
    {
    // do some stuff
    }

C# has always supported evaluating a single command after a branching expression, by the way. In fact, that's the only thing it does, even now. Putting code in braces after a branching expression just makes that one command a goto (the compiler creates scope using jmp instructions). C++, Java, C# and JavaScript are all more or less based on C, with the same underlying parsing rules, for the most part. So in that sense, C# is not "based on Java."

Summing up, this is a bit of a religious/flame-war issue. But there are studies making it pretty clear that arranging code in blocks improves human comprehension. The compiler couldn't care less. But this is also related to the reason why I never put a line of code after a branch without braces--it's just too easy for me or another programmer to slap another line of code in there later and slip on the fact that it will not execute in the same context with the line right before or after it.

EDIT: Just go look at the Apple goto fail bug for a perfect example of this exact issue, which had very serious real world consequences.

if( true )
    doSomething();

becomes...

if( true )
    doSomething();
    doSomethingElse();

In this case, doSomethingElse() executes every time, regardless of the outcome of the test, but because it is indented to the same level as the doSomething() statement, it's easy to miss. This isn't really arguable; studies back this up. This is a big source of bugs introduced into source code during maintenance.

Still, I'll admit that JavaScript closure syntax looks a little silly with braces on their own lines...aesthetically. :-)

ContentLicense: CC BY-SA 4.0


问:
Multiple models or a single model with multiple custom data types?
I am writting a small webapp for learning.

Is it better / best practice to create multiple models or one model with multiple custom data types? For example:

Let's say the web app is "PublicLibrary." The library would have shelves. Shelves would have books and locations. Books would have titles, authors, text and a dewey decimal number.

Would it be better to have a Book model, a shelf model (couldn't come up with a better example for this), and a Library model; or a book class, a shelf class, and a Library model that holds those classes. I understand that a model is a class, but hopefully my question makes sense.

答:
You should create classes for every object type that does not have a built-in type.

For example, a Library would contain Books, but a Book would likely use a built-in string type for the dewey decimal number (use a string because you are not performing math on it) and title. Author could be a string, but would likely be reused on multiple books and may have further properties so should stand alone as its own object.

We can provide better guidance if you could post a diagram showing your design along with specific questions regarding how to achieve your goal with the design.


问:
Why are more programmers not freelance these days?
Leaving the whole pie to only a few of them, amplifying the huge differences between the two status. Pay is a (huge) one, not having to do overtime is another.

I leave the question open to hopefully get many great answers on all the different subjects that affects that feeling and decision not to go.

While this question is really global, I'll be interested in any studies, facts, articles, opinions regarding local markets such as US, India and even Australia in which I'm in love with.

答:
I would love to work for myself, and even recently tried being a freelancer for 3 months earlier this year.  It didn't work out quite like I hoped, and after I got a good offer from a good company, I went back to full-time salaried employment.

These are the negatives I experienced while freelancing:

Writing code has become a commodity

Let's say I can make $X an hour (average) on salary.  Insurance benefits, stock options, bonuses, etc., generally make that $X * (1.2 to 1.35) or so, let's call that $Y.  Here in the US, as a freelancer, you pay approximately 7% higher taxes (you pay the extra Social Security your employer normally pays).  There is also the time you spend networking and bidding which you won't get paid for, and the cost of equipment.  So, I would give $X * 1.5 as my standard rate, and I would be negotiable down to $Y. Most contacts I was getting for work would tell me their budget was $X * 0.75 or less.

Of course, they shouldn't be budgeting at an hourly rate, since they have no idea how efficient I would be nor how much better off they would be with code that would last with their business, but I didn't have the time to put a case together to attempt to convince them otherwise.

I also bid on several projects online at a rate that would be sustainable for me ($Y), but I simply didn't get responses.  Online was even worse because I was competing in a real commodity market.  There were people from who knows which country where the cost of living is much, much less, with much less experience, bidding at probably 6 times lower or more than I was.

It's just not fun to work in a commodity marketplace.

Networking

I have many contacts, but just didn't have enough to consistently get work. This is a sub-point of commodity coding — if I was making much more per hour than on salary, this wouldn't be an issue, since I could spend a lot of my time networking and finding new jobs.  As it was, my margins on jobs I could get would be too thin to spend much time doing anything else.

Disposable projects

I like being able to build efficiency by spending time here and there on architecture, tools, and simply becoming very familiar with the project.  When you are working on projects that are only 40-100 hours each, you probably aren't going to be able to gain much efficiency over time, unless you are using your own frameworks for all of them, and even then, project knowledge doesn't really help you from one to the next.

When working at a company, on a team, you are (hopefully) building more for yourself and your career than just a checklist of past projects you've worked on.

I had one large project during the 3 months that I worked as a freelancer (I left my previous job by choice, hoping to really start working for myself).  Around the time I got paid for that job, I got two offers from good companies that were better than my previous job, and I decided I couldn't pass it up.

For these reasons, I can't see myself going back to working on my own unless I've got a software product of my own to build a company around.  And that I would love to do.


答:
As I hypothesized in this answer here - https://softwareengineering.stackexchange.com/a/159081/29029 - I suppose the decision to go with Allman's bracing could be a sign of Pascal heritage, given that Hejlsberg created Delphi before he designed C#. Same as Pascal case for method names.

Personally I believe in following the adage "in Rome do as Romans do". I use Allman's in C#, but K&R in Java. I am so used to it that switching the convention either way is jarring to me.

I believe that some convention diversity is actually beneficial for a "multilingual" developer as it helps to remember which language they're coding in at the moment and makes it easy to differentiate various habits. It's a mental equivalent of muscle memory, so to speak.


答:
Having a restriction on the interface such as,

... class DataImport with only two public methods

is valid and in no way implies that your design is not okay. In fact it would be bad to clutter the interface with methods intended for testing only.

Instead, you can use interface segregation to increase the testability of the class and present separate views.

The interface-segregation principle (ISP) states that no client should
  be forced to depend on methods it does not use. ISP splits
  interfaces which are very large into smaller and more specific ones so
  that clients will only have to know about the methods that are of
  interest to them. Such shrunken interfaces are also called role
  interfaces. ISP is intended to keep a system decoupled and thus
  easier to refactor, change, and redeploy. ISP is one of the five SOLID
  principles of Object-Oriented Design

Practically this means that you will create two interfaces, for example DataImportIf and DataImportIfInternal where the other interface will expose the relevant private methods or fields, and will be used either by the tester only or by classes which themselves constitute part of the DataImport state.

Title: How to test state of the object

Body:
I have a class DataImport
with only two public methods

```<code>public void fromStream(InputStream inputStream);
public ImportCommand getImportCommand();
</code>```

When I test it I send some test data to fromStream method

```<code>dataImport.fromStream(some stream with data...)
</code>```

Only way how to test the result of this method is to get the ImportCommand from getImportCommand and test if this object is in the state according to the input I provided.

But what if ImportCommand has only one method?

```<code>public ImportResult execute();
</code>```

I could test ImportResult (after invoking execute() which would involve some mocks and additional setup) because it has some state exposed. But this way I am testing ImportCommand and the DataImport class in one unit test which does not feel right to me.

But exposing inner state of the classes I am testing or accessing their private fields/methods also is not good thing.

Does this mean that my design is not ok (how should I change it) or is there some way how to solve this situation?

Related: TDD anti-patterns on SO


问:
Are there numbers that are not representable in base 10 but can be represented in base 2?
C# has the decimal type which is used for numbers that needs exact representation in base 10. For instance, 0.1 cannot be represented in base 2 (e.g. float and double) and will always be an approximation when stored in variables that are of these types.

I was wondering if the reversed fact was also possible. Are there numbers that are not representable in base 10 but can be represented in base 2 (in which case I would want to use a float instead of a decimal to handle them)?

答:
Once you get outside the range of acceptable values, the answer is yes. That said, almost anything inside the range will have a representation. C# Decimal reference While not stated in the specification, irrational numbers cannot be exactly represented (e.g., e1, pi, square root of 2, etc.).

The decimal keyword denotes a 128-bit data type. Compared to floating-point types, the decimal type has a greater precision and a smaller range, which makes it suitable for financial and monetary calculations. The approximate range and precision for the decimal type are shown in the following table.

Precision: 28-29 significant digits

1 Thanks to MichaelT for reminding me of another irrational number.


答:
Here's the key to your quandary: 10 is the product of 2 and 5.  You can represent any number exactly in base 10 decimals that is k * 1/2n * 1/5m where k, n and m are integers.

Alternatively phrased - if the number n in 1/n contains a factor that is not part of the factors of the base, the number will not be able to be represented exactly in a fixed number of digits in the binary/decimal/whatever expansion of that number - it will have a repeating part.  For example 1/15 = 0.0666666666.... because 3 (15 = 3 * 5) is not a factor of 10.

Thus, anything that is able to be represented in base 2 exactly (k * 1/2n) can be represented in base 10 exactly.

Beyond that, there is the issue of how many digits/bits are you using to represent the number. There are some numbers that are able to be exactly represented in some base, but it takes more than some number of digits/bits to do.

In binary, the number 1/10 which is conveniently 0.1 in decimal isn't able to be represented as a number that can be represented in a fixed number of bits in binary.  Instead, the number is 0.00011001100110011...2 (with the 0011 part repeating forever).

Lets look at the number 12/10102 a bit more closely.

```
          ____
       0.00011
     +---------
1010 | 1.00000
       0
       --
       1 0
         0
       ----
       1 00 ---------+
          0          |
       -----         |
       1 000         |
           0         |
       ------        | repeating
       1 0000        | block
         1010        |
       ------        |
          1100       |
          1010       |
          ----       |
            100  ----+
```

This is exactly the same type of thing you get when you try to do the long division for 1/3.

1/10, when factored is 1/(21 * 51).  For base 10 (or any multiple of 10), this number terminates and is known as a regular number.  A decimal expansion that repeats is known as a repeating decimal, and those numbers that go on forever without repeating are irrational numbers.

The math behind this delves into Fermat's little theorem... and once you start saying Fermat or theorem, it becomes a Math.SE question.

Are there numbers that are not representable in base 10 but can be represented in base 2?

The answer is 'no'.

So, at this point we should all be clear that every fixed length binary expansion of a rational number can be represented as a fixed length decimal expansion.

Lets look more closely at the decimal in C# which leads us to Decimal floating point in .NET and given the author, I'll accept that thats how it works.

The decimal type has the same components as any other floating point number: a mantissa, an exponent and a sign. As usual, the sign is just a single bit, but there are 96 bits of mantissa and 5 bits of exponent. However, not all exponent combinations are valid. Only values 0-28 work, and they are effectively all negative: the numeric value is sign * mantissa / 10exponent. This means the maximum and minimum values of the type are +/- (296-1), and the smallest non-zero number in terms of absolute magnitude is 10-28.

I'll point out right away that because of this implementation there are numbers in the double type that cannot be represented in decimal - those that are out of the range.  Double.Epsilon is 4.94065645841247e-324 which can't be represented in a decimal, but can in a double.

However, within the range that decimal can represent, it has more bits of precision than other native types and can represent them without error.

There are some other types floating around.  There is a BigInteger in C# which can represent an arbitrarily large integer.  There is no equivalent to Java's BigDecimal (which can represent numbers up with decimal digits of up to 232 digits long - which is a sizable range) exactly.  However, if you poke around a bit you can find hand rolled implementations.

There are some languages that also have a rational data type which allows you to exactly represent rationals (so that 1/3 is actually 1/3).

Specifcally for C# and the choice of float or rational, I'll defer to Jon Skeet from the Decimal floating pint in .NET:

Most business applications should probably be using decimal rather than float or double. My rule of thumb is that manmade values such as currency are usually better represented with decimal floating point: the concept of exactly 1.25 dollars is entirely reasonable, for example. For values from the natural world, such as lengths and weights, binary floating point types make more sense. Even though there is a theoretical "exactly 1.25 metres" it's never going to occur in reality: you're certainly never going to be able to measure exact lengths, and they're unlikely to even exist at the atomic level. We're used to there being a certain tolerance involved.

Body:
C# has the decimal type which is used for numbers that needs exact representation in base 10. For instance, 0.1 cannot be represented in base 2 (e.g. float and double) and will always be an approximation when stored in variables that are of these types.

I was wondering if the reversed fact was also possible. Are there numbers that are not representable in base 10 but can be represented in base 2 (in which case I would want to use a float instead of a decimal to handle them)?

Body:
Here's the key to your quandary: 10 is the product of 2 and 5.  You can represent any number exactly in base 10 decimals that is k * 1/2n * 1/5m where k, n and m are integers.

Alternatively phrased - if the number n in 1/n contains a factor that is not part of the factors of the base, the number will not be able to be represented exactly in a fixed number of digits in the binary/decimal/whatever expansion of that number - it will have a repeating part.  For example 1/15 = 0.0666666666.... because 3 (15 = 3 * 5) is not a factor of 10.

Thus, anything that is able to be represented in base 2 exactly (k * 1/2n) can be represented in base 10 exactly.

Beyond that, there is the issue of how many digits/bits are you using to represent the number. There are some numbers that are able to be exactly represented in some base, but it takes more than some number of digits/bits to do.

In binary, the number 1/10 which is conveniently 0.1 in decimal isn't able to be represented as a number that can be represented in a fixed number of bits in binary.  Instead, the number is 0.00011001100110011...2 (with the 0011 part repeating forever).

Lets look at the number 12/10102 a bit more closely.

          ____
       0.00011
     +---------
1010 | 1.00000
       0
       --
       1 0
         0
       ----
       1 00 ---------+
          0          |
       -----         |
       1 000         |
           0         |
       ------        | repeating
       1 0000        | block
         1010        |
       ------        |
          1100       |
          1010       |
          ----       |
            100  ----+

This is exactly the same type of thing you get when you try to do the long division for 1/3.

1/10, when factored is 1/(21 * 51).  For base 10 (or any multiple of 10), this number terminates and is known as a regular number.  A decimal expansion that repeats is known as a repeating decimal, and those numbers that go on forever without repeating are irrational numbers.

The math behind this delves into Fermat's little theorem... and once you start saying Fermat or theorem, it becomes a Math.SE question.

Are there numbers that are not representable in base 10 but can be represented in base 2?

The answer is 'no'.

So, at this point we should all be clear that every fixed length binary expansion of a rational number can be represented as a fixed length decimal expansion.

Lets look more closely at the decimal in C# which leads us to Decimal floating point in .NET and given the author, I'll accept that thats how it works.

The decimal type has the same components as any other floating point number: a mantissa, an exponent and a sign. As usual, the sign is just a single bit, but there are 96 bits of mantissa and 5 bits of exponent. However, not all exponent combinations are valid. Only values 0-28 work, and they are effectively all negative: the numeric value is sign * mantissa / 10exponent. This means the maximum and minimum values of the type are +/- (296-1), and the smallest non-zero number in terms of absolute magnitude is 10-28.

I'll point out right away that because of this implementation there are numbers in the double type that cannot be represented in decimal - those that are out of the range.  Double.Epsilon is 4.94065645841247e-324 which can't be represented in a decimal, but can in a double.

However, within the range that decimal can represent, it has more bits of precision than other native types and can represent them without error.

There are some other types floating around.  There is a BigInteger in C# which can represent an arbitrarily large integer.  There is no equivalent to Java's BigDecimal (which can represent numbers up with decimal digits of up to 232 digits long - which is a sizable range) exactly.  However, if you poke around a bit you can find hand rolled implementations.

There are some languages that also have a rational data type which allows you to exactly represent rationals (so that 1/3 is actually 1/3).

Specifcally for C# and the choice of float or rational, I'll defer to Jon Skeet from the Decimal floating pint in .NET:

Most business applications should probably be using decimal rather than float or double. My rule of thumb is that manmade values such as currency are usually better represented with decimal floating point: the concept of exactly 1.25 dollars is entirely reasonable, for example. For values from the natural world, such as lengths and weights, binary floating point types make more sense. Even though there is a theoretical "exactly 1.25 metres" it's never going to occur in reality: you're certainly never going to be able to measure exact lengths, and they're unlikely to even exist at the atomic level. We're used to there being a certain tolerance involved.


问:
How can I promote software reuse in a large company?
Take a large company, formed through many iterations of mergers and reorganizations. This company produces lots of different products that are all targeted to a specific industry. Most products share similar characteristics, such as communication standards and certification and safety requirements. But there is no unified development platform or model for the company. Each product has its own distinct hardware, and software is created in any number of languages. Most new products will be updates to older versions or target the same industry. What strategies would you use to promote software reuse?</p>

答:
The problem with code reuse is that code needs to evolve differently in different products.

Say that you have two products (1 and 2) that have some similar characteristics, and you then extract a library (L) out of them that contains those shared characteristics. Seems like a good idea: you now just improve the library, and the improvements go "automagically" to both products.

Then, over time, you build more products on top of that library. Eventually you have 10 products. You'll notice that changing the library has become an extremely stiff process. You have to consider all those 10 products when implementing a change, and after you've implemented it, you have to test it on all those products. What if some of the products now need to evolve differently, even though they were kind of similar in the start? You could either branch the library so that different products have their own versions of the library (no more sharing advantage), or start building all kind of switches, options, adapter layers and special cases to accommodate for all special needs in the single united codebase. The end resuld could be  a Big ball of mud.

It may be doable, but it's not as rosy as one might hope. At least it increases risk.


问:
Use model for “everything” in MVC?
This question is a result out of the discussion HERE and was moved from HERE.

Is it really good practice to supply EVERY value you display in any view via a model?

Especially variables like the current username. Even Microsoft odes the following in their default template for the _LoginPartial in ASP.NET MVC 3+:

```<code>"Hello " + User.Identity.GetUserName() + "!"
</code>```

I think this is OK to not supply this via a model as it is much better in light of maintainability. Or should you obay the "MVC rules" and add a model/sub-model to every page/model to supply such stuff and pass it around in your views and partials?

How do you solve such "problems" or what do you think is the best way of doing such stuff?

Inheritance would be an option:

```<code>public class BaseUserModel
{
    public string UserName { get; set; }
}
</code>```

Require every model to inherit from a base model like above containing such values.

But could that cause problems if you need/want to inherit another class for some model?

答:
User is a model, in the generic sense of the word, even if not according to Microsoft's narrower definition in their particular implementation of the MVC pattern.   You're not doing something like User.OutputGreeting(), so the model and view are still separated, with all the concomitant benefits.  The only thing you're missing out on is some of the sugar provided by the framework.

It doesn't make sense to put in more effort and more complexity to do something "the easy way."  Additionally, creating another model for something already provided violates design principles like single source of truth.

Title: Use model for “everything” in MVC?


问:
Design and relationship of a cursor and its referred object
I need to implement a Cursor class to perform operations on a Document object, which is implemented internally as a simple list of rows. The Cursor class must have methods such as moving around the Document, add lines, remove lines, insert text in a given position etc.

The problem I have is relative to the details of the design. To me, it seems that the cursor must know the implementation details of the referred class. In C++, these classes must be friend classes, but I don't like it for obvious reasons (encapsulation etc.). I can't envision an interface for the Document class to keep its implementation private that also doesn't defeat the purpose of a Cursor class, that is, I end up having the interface of the Cursor on the Document class itself.

Is leaking Document implementation details mandatory when implementing a Cursor? If not, what should the Document interface be?

答: In my opinion, it makes no sense to make Document an abstraction but have it be used through a separate class. If you intend to make the implementation of Document private, then the Cursor is part of the Document's public API - why not just get rid of the middleman and move those methods to the Document class?


问:
What algorithm should I use to create an automatic staff scheduling feature?
Imagine a small local business (in my case a dog daycare) with a few dozen part-time employees . The goal is to automatically create weekly staff schedules. My question is about what algorithmic approaches to explore for this problem.

There are many constraints to keep in mind, chiefly (1) the availability of the staff and (2) the needs of each shift, not just how many staff for each shift but the skills needed for each shift (e.g. for a certain shift, you may need someone who knows how to drive to do pick-ups/drop-off of dogs, for another, someone who know how to give dogs baths, etc).

Other constraints include things like avoiding or requiring certain staff combos -- perhaps due to personality conflicts on one hand, or need for training by osmosis from a senior to junior staff on the other.

Also, there are preferences to take into account. Some staff prefer mornings, some two days in a row rather than say Monday and Thursday, etc. We know we can't always accommodate everyone's preferences. In fact we have a hierarchy of which employees get first dibs on their choices.

I have a hunch that there is a way to reduce or express this problem into an existing, already solved algorithm. But I don't know which algorithms to explore. Which existing, specific algorithms would be most promising?

答:
Algorithms such as Local Search (Tabu Search, Simulated Annealing, Late Acceptance) work very well on such problems.

As Bob suggests, if you're working in Java, take a look at OptaPlanner (open source). See this video on employee rostering.


问:
Pattern matching in Clojure vs Scala
What are the key differences between pattern matching in these two languages? I am not referring to syntax, but capability, implementation details, range of use cases and necessity.

Scala applications (eg. Lift and Play) speak proudly about the languages pattern matching prowess. Clojure, on the other hand has a library, core.match, and built in destructuring, which also seems powerful.

*note: The reason I was inspired to ask this question is because of a blog post I saw in which a programmer, as an experiment, built a lisp interpreter using both Scala and Clojure. He said that the Clojure matches broke after a certain length, but could not explain why, but I am really curious to know. You can find this post here:
http://www.janvsmachine.net/2013/09/writing-simple-lisp-interpreter-in-clojure.html

答:
In this video I watched recently, Rich Hickey comments that he likes the destructuring part of languages like Scala, but not so much the pattern matching part, and he designed Clojure accordingly.  That probably explains why the pattern matching is in a library and not as robust, although the kind of problems seen in the post you mentioned are clearly bugs.

What Rich Hickey mentions as an alternative to pattern matching is multimethods.  Most languages let you do polymorphic dispatch based on type.  Some languages let you also do it based on a value.  Using multimethods, Clojure lets you do it based on any arbitrary function.  That's a pretty powerful concept.

It comes down to the principle that programmers using a language should use the language's own best idioms.  Trying to write Scala-like code in Clojure is going to have its difficulties, and vice versa.

Title: Pattern matching in Clojure vs Scala


问:
Error Handling when no access to Visual Studio or application start point
I've recently joined a project where we are extending the functionality of an external application that our company has bought.

It is an Office Add-In with an admin console that allows you to create Windows Forms style forms with code-behind files, and gives you a single place to store common code. This can be quite challenging when implementing code that would be simple in a 'normal' Windows Forms application.

How do I implement global error handling so we can log all errors?

We aren't using Visual Studio and have no access to csproj files so we can't use IL weaving / AOP. We don't have access to the starting point of the application so we can't subscribe to thread or application unhandled exception events. I suspect this is already being subscribed to in the external code, as unhandled exceptions are exposed in a custom error message box by default.

I'm currently looking to see if we can extend the external dlls; however I don't see where I'm going to call our extended code.

The alternative is to go through every method and add a try/catch block in just to log errors, which makes my skin crawl! This project has been running for a year without dealing with error handling yet so it will also take a long time to implement this approach too.

Pseudo-Example class:

```<code>namespace Scriptlets
{
  using System;
  using System.Windows.Forms;

  public partial class NewClient : FormScriptType
  {
    protected override void PageChanged(object sender, PageChangedEventArgs e)
    {
        ChangeAddressLabels();
    }

    ...
  }
}
</code>```

答:
About the logging - if you want to spare some typing of try/catch blocks, you could create one method that takes a Func or Action and wraps the execution in a try/catch block:

```<code>public T ExecuteAndLogIfFail<T>(Func<T> action)
{
    try
    {
        return action();
    }
    catch (Exception exception)
    {
        Console.WriteLine("Implement your logger here: {0}", exception.Message);
    }
    return default(T);
}
</code>```

You can now wrap your new code into this and you will always have exception handling.

Usage of the wrapper:

```<code>ExecuteAndLogIfFail<Boolean>(() =>
{
    Console.WriteLine("Do something without output");
    return true;
});

var zero = 0;
List<Int32> items = new List<Int32> { 10, 20, 30, 40, 50 };
var result = ExecuteAndLogIfFail<Int32>(() =>
{
    return items.Sum(i => i / 10);
});
Console.WriteLine(result);

ExecuteAndLogIfFail<Boolean>(() =>
{
    result /= zero; // catch and log!
    return true;
});
</code>```

If you haven't tried this already you could experiment with the AppDomain.CurentDomain object and hook the unhandled exception event:

```<code>AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
    Console.WriteLine("something happened ...");
};
</code>```

If you figured out, that the new window launch is wrapped in a try/catch block, you could try to modify (if this is ok) the assembly using Cecil and add a throw statement into the catch block. I once used the Reflexil Reflector plugin to inject code into an assembly and save the modified executable - no app start points needed. The plugin site states, that it works with Telerik's JustDecompile too.

The conclusion is - maintaining closed legacy systems is PITA. :-)

Body:
About the logging - if you want to spare some typing of try/catch blocks, you could create one method that takes a Func or Action and wraps the execution in a try/catch block:

public T ExecuteAndLogIfFail<T>(Func<T> action)
{
    try
    {
        return action();
    }
    catch (Exception exception)
    {
        Console.WriteLine("Implement your logger here: {0}", exception.Message);
    }
    return default(T);
}

You can now wrap your new code into this and you will always have exception handling.

Usage of the wrapper:

ExecuteAndLogIfFail<Boolean>(() =>
{
    Console.WriteLine("Do something without output");
    return true;
});

var zero = 0;
List<Int32> items = new List<Int32> { 10, 20, 30, 40, 50 };
var result = ExecuteAndLogIfFail<Int32>(() =>
{
    return items.Sum(i => i / 10);
});
Console.WriteLine(result);

ExecuteAndLogIfFail<Boolean>(() =>
{
    result /= zero; // catch and log!
    return true;
});

If you haven't tried this already you could experiment with the AppDomain.CurentDomain object and hook the unhandled exception event:

AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
    Console.WriteLine("something happened ...");
};

If you figured out, that the new window launch is wrapped in a try/catch block, you could try to modify (if this is ok) the assembly using Cecil and add a throw statement into the catch block. I once used the Reflexil Reflector plugin to inject code into an assembly and save the modified executable - no app start points needed. The plugin site states, that it works with Telerik's JustDecompile too.

The conclusion is - maintaining closed legacy systems is PITA. :-)


答:
A base-two floating-point type would be able to precisely represent many values which a base-ten type of the same size could not.  Any value which would be exactly representable by a base-2 type of some size would be exactly representable in a base-ten type of sufficient size.  The required size for a purely-base-ten type to represent all values of a binary floating-point number would depend upon the exponent range of the binary type; hundreds of bits for a float, or thousands for a double.

That having been said, the Decimal type is large enough that it would have been possible to make usable as a "universal" type capable of holding the value of any other numeric primitive and provide some other additional features besides (if nothing else, use one bit to indicate whether the stored value is the result of converting a double, and if that bit is set, use 64 bits to hold the value in question).  Microsoft opted not to do that, however.  As a result, conversion of a double to Decimal will fail completely for large values, will cause small values to be rounded to the nearest 1E-28.  Further, even within the dynamic range of decimal, the conversion method will not "round-trip".  For example, evaluating 1.0/3.0 as double will yield 0.3333333333333333148, but converting that to decimal will yield 0.333333333333333m and converting that back to double would yield 0.3333333333333329818.

Title: Are there numbers that are not representable in base 10 but can be represented in base 2?


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
Booting from a live CD/DVD (physically or in a VM) makes me feel a lot better about allowing Flash and JavaScript to do their thing.  If I remember correctly Linux Mint has Flash support out of the box.

As far as site development, I usually do a reasonable amount of div swapping and menus in JavaScript, but I try to make everything look right and basically work with CSS.


问:
Strategy for maintaining offline repository safely using git
I use git for versioning. Just yesterday I was working on refactoring my Python code base. After adding a test I found that I had introduced a bug in one of project euler solutions. So I checked out a previous version offline, found the diff and went back to latest version and fixed the problem.

It was a bit after that I found a mess up had been done due to this. I use .gitignore to leave many of the unneeded files or WIP things out of git. I found that using checkout and going back to the latest version deleted some files which were not checked in. Now I am finding that a new repo that I keep in an ignored Folder is completed cleaned. It did not have much so far but still all is gone.

So I am confused about what is a good way to keep offline codebase intact in case there are many such folders/files that I do not want to check in? Also how to organize codebase on local for new projects? Just take backups on a drive?

答:
git does warn you if it is going to modify or delete untracked or uncommitted files. Don't take this lightly.

Do check in everything you work on, all WIP stuff, all temporary stuff. If you can't carelessly delete a file outright, track it. Make a lot of small commits. Once something started to work, commit it; don't mind that it's yet imperfect.

If you care about cleanliness, use separate branches: keep 'master' clean and wildly experiment on feature branches. Branching is incredibly cheap in git. When you want to pull a feature in, use merge or cherry-pick.

If amidst a change you need to check out another commit, git stash is your friend. You can git stash pop on the same or on a different branch; great when you just realized that you had started working on a wrong branch.

And again, look at all your untracked files as useless trash that a janitor may choose to take out at any moment. If something is not trash, git add it.


答:
Ok, two myths there:
1) Pay - it may look like there are wide gaps but there are a lot of hidden costs to employing someone that a contractor or freelancer has to bear for themselves
2) No overtime. Really? It may not be called overtime but you're not liable to have to work any less hard.

On top of which - depending on location - employees get paid holiday and all sorts of other benefits (e.g. pensions, paid sick leave) that freelancers have to fund themselves (c.f. hidden costs above).

Further, a freelancer has to do all the stuff that programmers often struggle with - find business in the first place, manage the work they have, invoice, chase invoices, chase invoices some more (getting paid is much, much easier when the company runs a payroll every month), deal with taxes and expenses and capital allowances and all sorts of things that you tend not to have to worry about as an employee.

Title: Why are more programmers not freelance these days?

Body:
Leaving the whole pie to only a few of them, amplifying the huge differences between the two status. Pay is a (huge) one, not having to do overtime is another.

I leave the question open to hopefully get many great answers on all the different subjects that affects that feeling and decision not to go.

While this question is really global, I'll be interested in any studies, facts, articles, opinions regarding local markets such as US, India and even Australia in which I'm in love with.


问:
Is there an API for determining congressional districts?
I'm looking to determine the congressional district based on an address my user is providing. This will avoid having the user to look it up themselves.

Does an API of this sort exist?

Note

Through my attempts to find one, I've only come across these:

http://www.govtrack.us/developers/api

(not sure how to submit an an address or zip code however)

The following resources are available in the API

...Bills and resolutions in the U.S. Congress since 1973 (the 93rd Congress).

...A (bill, person) pair indicating cosponsorship, with join and withdrawn dates.

...Members of Congress and U.S. Presidents since the founding of the nation.

...Terms held in office by Members of Congress and U.S. Presidents. Each term corresponds with an election, meaning each term in the House covers two years (one 'Congress'), as President four years, and in the Senate six years (three 'Congresses').

...Roll call votes in the U.S. Congress since 1789. How people voted is accessed through the Vote_voter API.

...How people voted on roll call votes in the U.S. Congress since 1789. See the Vote API. Filter on the vote field to get the results of a particular vote...

http://www.opencongress.org/api

(seems to be a way to find congress information, but not districts)

This API provides programmers with structured access to all the data on OpenCongress, everything from official bill info to news and blog coverage to user-generated votes on bills and much more...

This API defaults to returning XML. All queries can also return JSON...

https://groups.google.com/forum/?fromgroups=#!topic/opendems-discuss/CeKyi_aANaE

(similar question, no resolution)

I've been looking over Open Dems, and seeing what's exposed at this
  point and what isn't.  I work with Democrats Abroad, and am interested
  in using stuff from the lab for their sites.

I quickly looked over the Precinct API, which does both more and less
  than what I'd need.  An ideal resource would be any way of translating
  addresses into CD at the very least (getting state district data would
  be good as well), since that would make it easier for DA's membership
  to make a difference in races like last month's NY26 race...

Update

I'm looking at the source for the govtrack.us website and the 'doGeoCode' function may be useful.

view-source:http://www.govtrack.us/congress/members

If no one has any suggestions, I will try to go off of what they are doing.

答:
I realize this question is old, but I figured I'd throw in my two cents for anyone who might still be looking.

First, some background info. Congressional districts are extremely specific - down to an address itself, not just the street. Me and my neighbor across the street could be in different congressional districts. This is why it's so important to get a good ZIP+4 code to ensure that you're placing the address in the correct district. A system (like SmartyStreets or Melissa Data or QAS, etc.) that does address validation would give you a reliable ZIP+4 to ensure that the district is correct.

SmartyStreets has their LiveAddress API, which returns congressional data along with over 40 other data points (geocodes, residential vs commercial, etc.).


问:
To which level Haskell's HDBC is lazy?
The HDBC documentation states:

fetchAllRows :: Statement -> IO [[SqlValue]]Source

Lazily fetch all rows from an executed Statement.

You can think of this as hGetContents applied to a database result
  set.

The result of this is a lazy list, and each new row will be read,
  lazily, from the database as the list is processed.

When you have exhausted the list, the Statement will be finished.

Please note that the careless use of this function can lead to some
  unpleasant behavior. In particular, if you have not consumed the
  entire list, then attempt to finish or re-execute the statement, and
  then attempt to consume more elements from the list, the result will
  almost certainly not be what you want.

But then, similar caveats apply with hGetContents.

Bottom line: this is a very convenient abstraction; use it wisely.

Use fetchAllRows' if you need something that is strict, without all
  these caveats.

Then, I wonder, to which level does the laziness extend?

Say, I can have

```<code>  conn <- connectSqlite3 databaseFilePath
  rows <- quickQuery conn ("SELECT * FROM foo") []
  mapM_ bar $ take n rows
  disconnect conn
</code>```

Will it actually only fetch n rows? Like, from the database point of view, will it be equivalent of SELECT * FROM foo LIMIT (n)? Because fetching all rows at the level of database driver and then takeing n of them seems to be silly and kind of defeats the purpose.

If it's lazy up to the database itself, how's it implemented? Is it using cursors?

I know there're several drivers for HDBC alone. I'm asking only about principle of implementation.

答:
I suspect (though I can't verify) that they're relying on the standard ODBC capability for the data-streaming based on the fact that the documentation says it supports

[...] and have it work with any number of backend SQL databases (MySQL, Oracle, PostgreSQL, ODBC-compliant databases, etc.) [...]

(emphasis mine)

If you'll have a look at MSDNs generic non-DB-specific ODBC API you'll see it has streaming data reader facilities.

Given this, I assume the ODBC standards dictate lazy data streaming facilities, and the HDBC likely just relies on that (possibly with DB-specific heuristics for some particular DB's that may be beneficial beyond what ODBC supplies).

Title: To which level Haskell's HDBC is lazy?


答:
I imagine that every one of us wants stability and freelancing isn't exactly the same as an 8 hours job where you know that at the end of the month you will have an $$$ fat paycheck. Also, when freelancing you will probably spend a lot of time looking for work, dealing with contracts, clients etc.

I, for one, would prefer a stable job and income even if sometimes I'll have to work extra hours.


问:
Managing client-side and server-side validations in one place
I'm 100% on board with the case that one should definitely use both client-side and server-side data validations.

However, in the frameworks and environments I've worked in, the approaches I've seen have never been DRY. Most of the time there's no plan or pattern - validations are written in the model spec, and validations are written in the form on the view. (Note: Most of my first-hand experience is with Rails, Sinatra, and PHP w/ jQuery)

Mulling it over, it seems like it would not be difficult to create a generator which, given a set of validations (e.g. model name, field(s), condition), could produce both the necessary client-side and server-side material. Alternately, such a tool could take the server-side validations (such as the validates code in an ActiveRecord model) and generate client-side validations (such as jQuery plugins, which would then be applied to the form.

Obviously, the above is just a "hey I had this idea" musing, and not a formal proposal. This sort of thing is surely more difficult than it seemed when the idea hit me.

That brings me to the question: How would you approach designing a "write once, run on server and client" technique for data validation?

Related subtopics: Do tools like that exist for any particular frameworks or client-server technologies? What are major gotchas or challenges with trying to maintain only one set of validations?

答:
In my limited experience, the points where validation are required are

The presentation level using HTML,

at the post-presentation level (i.e., Javascript validation),

at the combination level where interactions between multiple fields have to be validated
    together,

at the business logic level and

at the database level.

Each of them have different languages, timings, and triggers. For instance, it makes little sense to validate a field before the entire record is in a consistent state, unless you want to validate just one piece. Constraints at the database level have to be applicable only at the end before a commit, and cannot readily be done piece-wise.

A related concept is that representing data varies between each of the levels. A simple example is a web browser represents a piece of text as, perhaps, CP1290, while the database represents it in UTF-8; the lengths of the two strings differ so enforcing length constraints gets awkward.


问:
Are there any algorithms for splitting or combining words into their more common form?
Are there any existing algorithms which can look through a list of words and split or combine words into their more common form?

For example, I have a list of many business names in the health care industry. The word "healthcare" is often written "health care". There are also business names which might be split or combined, such as "Walmart" and "Wal mart".

Are there any algorithms which can look at my list of words and identify that "healthcare" is more often written as two words, and that "Wal mart" is more often written as a single word?

I'm looking for the names of existing algorithms (which can help when searching the web), or links to existing white-papers or blog posts.

I'd prefer an algorithm that doesn't depend on a dictionary or other external list of words or business names.

EDITS:

Background:

I already have some code that is moderately successful at this task. The code was thrown together without much rigor. I hoped there were some established algorithms, which would likely be more academic and complete then what I've come up with. This question is not about the method I've come up with, but saying "it's impossible" doesn't convince me.

Clarification:

The "more common form" of a word is the way the word(s) are most often written. For example, "Walmart" appeared many times, and "Wal mart" appeared many times, but "Walmart" appeared more often then "Wal mart" and so "Walmart" is the "more common form" of the word.

I don't expect this algorithm to produce perfect results. Like any machine learning problem, I expect the results to be dependent on the quality of data I give it, and how much data I have.

答:
A quick search for "common compound words" revealed a few sites like this:

http://www.learningdifferences.com/Main%20Page/Topics/Compound%20Word%20Lists/Compound_Word_%20Lists_complete.htm

The problem here is that not all ("notall"?) compound words are legal. So at least, a validation check would require a lookup of each of the pieces against a dictionary (easy), a lookup of the compound word against a dictionary (easy), and a lookup against your list of validated compound words (easy). The missing piece is a confirmed mapping between the legal compound words and its pieces.

To split:

lookup the work in the compound words list, then iterate through each possible split & lookup each piece in a dictionary: ("n otall", "no otall", "not all", ...) to determine the split.

To join:

just concantenate & then lookup in a dictionary & in the legal words list.

In the long run, you might end up using a sort of Markov chain & Bayesian probability to determine the likelihood of an appropriate split, and slowly over time add to the "common" list of words with the ones you consider legal.

Or more simply, each time you see a word that cleanly splits into two words in the dictionary, add a mapping entry between the word and those pieces. There will often be more than one for a word. After that, each time you see that compound word again, give each of its mappings a "yes" vote. Each time you see the pieces separately, add a "no" vote to that mapping. Over time, you'd build up a list of mappings with a sense of the probability of it appearing in use.

I don't know know how large that list would get; in English, I doubt it would really grow to be that large. And you'd only have to create a legal compound-to-split mapping once.

...

If you had a mapping between compound and split, and carried values for "compound count" and "split count" for each mapping item, then the probability that the compound usage is prevalent is just compound_usage / sum(compound_usage + split_usage). You could leverage this the probabilistic way by generating a uniform random, and if less than that probability, print the compound, otherwise print the split version. Or you could just set a threshold (say 80%) and use some Bayesian smoothing to account for low frequency items.

Ultimately, there's nothing in the language that determines if a compound is "correct" -- it's convention and usage. It probably even varies regionally. So one way or another you're going to have to use some sort of sampling / probability estimation process to build a dictionary of compound words.

(Actually that sounds like kind of a fun project; I may play around with that.)

...

Since building the mapping would be a one-time task for each compound word, another alternative would be to farm the verification of the compounds & splits out to the Mechanical Turk: https://www.mturk.com/mturk/welcome Ultimately, that might be easier than trying to train and tune a fancier ML algorithm that really just needs to run once for each possible combination.


问:
Organizing uncommented, dirty code?
I would like to ask you some questions about dirty code. There are some beginners who coded on a medium project. The code is a very huge ball of mud. They are not advanced programmers. They just know how to use keyboard an a little about java. They just wrote code with 12 000 lines in their main class, though, 6 000 lines belongs to NetBeans itself.

My job is to analyze the code and suggest a good way to maintain the code. My idea is to scrap the project and start a new one with OOP methodology. Recently I collected some notes and ideas about the problem, from this site and some others.

Now, I have the followings questions:

Should we repair the code, and change it to a OOP? We are now debugging it.

The code has no comments, no documentation, no particular style of programming, and so forth. Changing it is really expensive and time consuming. What do we can do about this?

How can I teach them to follow all the rules (commenting, OOP, good code quality, etc.)?

The code is erroneous and error prone. What can we do? Testing? We almost write two or three A4 papers for correction, but it seems endless.

I should have to say that I am new with them. I think I have broken the rules about adding people too late to the project, as well. Do you think I have to leave them?

答:
Step 0: Backup to SCM

Because, as hinted to by JBRWilkinson in the comments, version control is your first line of defense against (irreversible) disaster.

Do also backup software configuration details, procedures to create deliverables, etc...

Step 1: Test First

Then start by writing tests:

for what works,

and for what fails.

No matter what you decide to do, you're covered. You can now either:

start from scratch and re-write,

or fix it.

My advice would be to start the general architecture from scratch, but extract from the mess the parts that validate checkpoints and to refactor these as you see fit.

Step 2: Verify and Monitor

Set up a Continuous Integration system (to complement step 0 and step 1) AND a Continuous Inspection system (to prepare for step 4).

Step 3: Stand on the Shoulders of Giants

(as you always should...)

Refactoring to Patterns

Refactoring: Improve the Design of Existing Code.

Working Effectively with Legacy Code  (as recommended by Jason Baker)

Refactoring

Step 4: Clean

That sort of goes without saying, but instead of skimming though the code yourself, you may want to simply run linters / static analyzers and other tools on the broken codebase to find errors in the design and in the implementation.

Then you might also want to run a code formatter, that will already help a bit with the housekeeping.

Step 5: Review

It's easy to introduce tiny bugs by refactoring or cleaning things up. It only takes a wrong selection and quick hit on a key, and you might delete something fairly important without realizing at first. And sometimes the effect will appear only months later. Of course, the above steps help you to avoid this (especially by implementing a strong test harness), but you never know what can and will slip through. So make sure to have your refactorings reviewed by at least one other dedicated pair of eye-balls (and preferably more than that).

Step 6: Future-Proof your Development Process

Take all of the above, and make it an inherent part of your usual development process, if it already isn't. Don't let this happen again on your watch, and work together with your team to implement safeguards in your process and enforce this (if that's even possible) in your policies. Make producing Clean Code a priority.

But really, test. A lot.

Title: Organizing uncommented, dirty code?


问:
Should I be using OOCSS in a CSS theme?
I have heard of OOCSS some time ago, but never really looked into it. Today I did so, and I thought of the implications of applying OOCSS to a simple CSS theme. One problem I thought of is that, by its nature, OOCSS encourages DRYness and consequently the use of many concise classes that should be applied to elements by the HTML developer. As a CSS theme, I would assume it isn't something significant enough for a developer would go out of his/her way to add specific classes to their elements when writing HTML:

```<code><button class="blue rounded no-border $etc">Button</button>
</code>```

as opposed to:

```<code><button>Button</button>
</code>```

Perhaps the HTML developers would be OK with writing the extra code, although it seems there is just as much repeating code on the HTML side as there would be without OOCSS.
So, is OOCSS not a one-size-fits-all methodology for writing CSS code, as in this example? Or am I not understanding things properly?

答:
I think that OOCSS by way of your example is an anti-pattern that does not provide a clear separation of concerns (html vs css) and does not provide you with semantic html nor css.

The separation of concerns is that HTML is concerned with the structure of a document, while CSS is concerned with how that document is presented.

```<code><button class="green rounded no-border">Save</button>
<button class="grey rounded no-border">Cancel</button>
</code>```

With the following css:

```<code>.green {
    color: #0f0;
}

.grey {
    color: #777;
}

.rounded {
    border-radius: 5px;
}

.no-border {
    border: none;
}
</code>```

Violates this separation of concerns by having the HTML document indicating that the save button should be green (instead of CSS telling it).

While OOCSS is designed to reduce the amount of code you write, it ends up being a maintenance nightmare by having to declare many (not semantic) classes.  Suppose you want later all your save buttons to be blue instead, are you going to change your green class to be blue, or are you going to do a ctrl+f in all your source files and update the text green to blue?

A good way to introduce reusability while still retaining semantic HTML / CSS is to use a CSS compiler (like less.js for example).

```<code><button class="primary-action">Save</button>
<button class="cancel-action">Cancel</button>
</code>```

With the following less.js:

```<code>/* these are reusable variables */
@primary-action-color: #0f0;
@cancel-action-color: #777;

/* this is a re-usable "mixin" */
.rounded() {
    border-radius: 5px;
}

button {
    border: none;
    .rounded;

    .primary-action {
        color: @primary-action-color;
    }

    .cancel-action {
        color: @cancel-action-color;
    }
}
</code>```

While it is more code initially, when you start reusing these variables / mixins you will be able to benefit from the semantic HTML and organized CSS.  For example, because the cancel-action has a good meaningful name, you can already add functionality to your app that makes sense.  Take for example the following jQuery.

```<code>$("button.cancel-action").click(function(e){
    if (!confirm('are you sure you want to cancel?')) {
        e.preventDefault();
    }
});
</code>```

Title: Should I be using OOCSS in a CSS theme?

Body:
I think that OOCSS by way of your example is an anti-pattern that does not provide a clear separation of concerns (html vs css) and does not provide you with semantic html nor css.

The separation of concerns is that HTML is concerned with the structure of a document, while CSS is concerned with how that document is presented.

<button class="green rounded no-border">Save</button>
<button class="grey rounded no-border">Cancel</button>

With the following css:

.green {
    color: #0f0;
}

.grey {
    color: #777;
}

.rounded {
    border-radius: 5px;
}

.no-border {
    border: none;
}

Violates this separation of concerns by having the HTML document indicating that the save button should be green (instead of CSS telling it).

While OOCSS is designed to reduce the amount of code you write, it ends up being a maintenance nightmare by having to declare many (not semantic) classes.  Suppose you want later all your save buttons to be blue instead, are you going to change your green class to be blue, or are you going to do a ctrl+f in all your source files and update the text green to blue?

A good way to introduce reusability while still retaining semantic HTML / CSS is to use a CSS compiler (like less.js for example).

<button class="primary-action">Save</button>
<button class="cancel-action">Cancel</button>

With the following less.js:

/* these are reusable variables */
@primary-action-color: #0f0;
@cancel-action-color: #777;

/* this is a re-usable "mixin" */
.rounded() {
    border-radius: 5px;
}

button {
    border: none;
    .rounded;

    .primary-action {
        color: @primary-action-color;
    }

    .cancel-action {
        color: @cancel-action-color;
    }
}

While it is more code initially, when you start reusing these variables / mixins you will be able to benefit from the semantic HTML and organized CSS.  For example, because the cancel-action has a good meaningful name, you can already add functionality to your app that makes sense.  Take for example the following jQuery.

$("button.cancel-action").click(function(e){
    if (!confirm('are you sure you want to cancel?')) {
        e.preventDefault();
    }
});


问:
Can someone explain the behind-the-scenes process of connecting an app account to a Facebook account?
I am developing an app that will use the Twitter and Facebook login APIs exclusively.

Suppose a new user downloads the apps and is presented with the option to log in through Facebook or Twitter. The user chooses Facebook.

I think the procedure at this point is to

a) create an auto-generated user ID in my Users table

b) store the Facebook credentials against the auto-generated user ID

I am confused about part b. Does Facebook return a unique ID when their API is called that I can store against my user ID or is there some alternate process? In other words, what exactly does it mean to store the Facebook credentials?

答:
You're talking about OAuth I imagine...  specifically 3 legged

https://dev.twitter.com/docs/auth/3-legged-authorization

Overview

The 3-legged OAuth flow allows your application to obtain an access token by redirecting a user to Twitter and having them authorize your application. This flow is almost identical to the flow described in Implementing Sign in with Twitter, with two exceptions:

The GET oauth/authorize endpoint is used instead of /oauth/authenticate
The user will always be prompted to authorize access to your application, even if access was previously granted.

b) store the Facebook credentials against the access token

I am confused about part b. Does Facebook return a unique ID when
  their API is called that I can store against my user ID or is there
  some alternate process? In other words, what exactly does it mean to
  store the Facebook credentials?

You're storing the access token provided by Twitter

you still will have your own user table if your application requires it.