答:
Einstein's Razor applies for the general case, whether you're making a simple website or a massive multi-purpose applicaiton.

It can scarcely be denied that the supreme goal of all theory is to make the irreducible basic elements as simple and as few as possible without having to surrender the adequate representation of a single datum of experience

You'll likely find the simplified form far more quotable: Everything should be made as simple as possible, but no simpler.

When you are creating a new system and have the choice between two development models, always select the one which leaves the system simpler unless you have a compelling reason to introduce the complexity.  This compelling reason should be documented in such a form as to make sense to whomever inherits your code.

Unfortunately, it sounds like your specific case is an existing system that has become more complex over time.  This leads you into the opposite principle, specifically If it ain't broke, don't fix it.  A system that works should be left as-is, until it either breaks or a replacement is ready.

The question as to when you should replace vs. simply continue on is a management one, and really comes down to the cost in actual or opportunity dollars spent to maintain the considerable technical debt you have in the old system against the cost it would take to design, develop, deploy, convert, and support a new system.


问:
Abstract Class confusion
I have learnt so far that abstract classes can't be instantiated because they are only there for other classes to inherit from. But i cant get my head around this code i came across in the msdn library:

```<code>WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
</code>```

in the documentation it says the above code returns a WebRequest instance.

but the WebRequest class is an abstract class, and how comes the above code returns an instance of an abstract class when abstract classes can't be instantiated.

please relieve me from my agony.

答:
Most likely, the Create method in that example will return an instance of a subclass of WebRequest.

To see exactly what you're getting back, you could try something like this:

```<code>WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
Type t = myRequest.GetType();
Console.WriteLine(t.Name);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Abstract Class confusion

Body:
Most likely, the Create method in that example will return an instance of a subclass of WebRequest.

To see exactly what you're getting back, you could try something like this:

WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
Type t = myRequest.GetType();
Console.WriteLine(t.Name);


答:
Abstract classes can't be instantiated immediately. That is, you can't do new SomeAbstractClass(). However, you can instantiate subclasses of an abstract class. So abstract classes are similar in function to interfaces, except that they can contain method definitions and member fields.

As such, abstract classes are great for introducing a level of abstraction. The WebRequest class is a good example here: It has subclasses for various protocols such as HTTP or HTTPS. When you instantiate a request via WebRequest.Create("https://example.com/"), you get a web request instance that can handle the HTTPS protocol, but is also a WebRequest instance. The static method Create(…) is a factory method.

See also the documentation for WebRequest.Create(…)

Title: Abstract Class confusion

Body:
I have learnt so far that abstract classes can't be instantiated because they are only there for other classes to inherit from. But i cant get my head around this code i came across in the msdn library:

```<code>WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
</code>```

in the documentation it says the above code returns a WebRequest instance.

but the WebRequest class is an abstract class, and how comes the above code returns an instance of an abstract class when abstract classes can't be instantiated.

please relieve me from my agony.


问:
Heuristics for absolutely-positioned GUI design - are multiples of 5 a good idea?
Disclaimer: I do not specialize in [desktop] GUI design, but have to do it on occasion. I have seen co-worker's dialogs worse than the once I created, and my major problem with them is that they can be unnecessarily big, and things do not line up.

To be more specific, I mostly do it in .Net Winforms, but occasionally with MFC(C++) as well. My simple heuristic so far is: I try to make the sizes and positions divisible by 10 ... or 5 if I have to. Something like a Label would be an exception, for it knows its own size. I find that things mostly look OK after I am done (of course there are other considerations such as grouping things intelligently, etc.), and I am satisfied because I know that every control has non-random position, and my OCD can now go back to sleep.

Somewhere at work I found a guide from MSFT about ideal spacing between things. Sorry, I do not have a source for it available. It has many rules, such as (for instance) 2 pixels between a button and a border, 3 pixels between two buttons horizontally, 4 pixels vertically, unless ... it is pretty complicated and not practical to remember. Additionally, I simply do not trust that MSFT knew much about GUI design, not until they hired an ex-apple person to help them design the ribbons for Office 2007, etc.

What rules/heuristics do you follow? References to short articles and other links are welcome.

答:
Forget about "nice round numbers", you will have to experiment with spacing to get something that looks nice, a fixed multiple just gets in the way.

I'd have to say that MSFT programs do tend to look pretty polished when it comes to such details, so despite your disbelief I would guess that the guide you found is probably pretty competent. Whether the higher level interface is clever or the graphical elements look good are different questions.

ContentLicense: CC BY-SA 2.5


问:
OOP: Behavior + Data, but what about 'validation' behaviors?
EDIT: Thanks for all the great answers! In reading these responses I realized that I'm approaching this from the wrong angle so I wrote a new question here.

I had this discussion with my superior about whether validation rules should be in the domain model or not (specifically, in the property accessors) and I tend to lean towards putting them just about anywhere else but there. In my opinion, put them in the UI and in the brokers/persistence layer.

The argument in favor of putting it in the domain is to 'protect the data' because data is king and long after the application code has been replaced the data will still be there. And also because "object oriented programming is about coupling data and behavior".

So take, for example, an object that represents a scheduled item with a StartTime and EndTime and a validation rule that says the StartTime must be before the EndTime (and the EndTime must be after the StartTime). Then while programming this you repeatedly run into issues as you realize things like:

Shoot, I forgot StartDate/EndDate could be equal too and my code errors on half the data it tries to load from the database

Ok so apparently the StartDate has to be set before the EndDate or my EndDate validation fails. Seems odd that I can't set properties like these in any order but ok.

Or... I could add more code to check if the StartDate is null and allow the EndDate to be set to anything so long as StartDate hasn't been set yet. Ok I'll do that.

But wait, unless I force the user to use a constructor with 10 parameters I can't absolutely ensure that there won't be any uninitialized properties because my validation logic will never get hit if they don't call the properties in the first place!

Poop, I tried forcing the consumer to use ridiculously verbose constructors but now I'm having serialization headaches. The DataContractSerializer that WCF uses totally ignores my constructor. I'm sure there's a way around this though, I'll figure it out.

Except now I want to use Sql Sessions and by default it uses an XmlSerializer that requires a parameterless constructor.

Uh oh, bad data has been imported into the database without going through my perfectly crafted domain model. Now my domain model prevents me from displaying this invalid data to the user so I have to correct it all myself. It would be great if I could jut allow them to correct it, but my domain model doesn't know how to do anything but crash when it reads invalid data.

So here's what I'm trying to figure out: are 'validation rules' really 'behaviors'? Technically they are, but in regard to the idea that "object oriented programming is data + behavior", does this really apply to validation?

答:
Programming isn't an exact science (at least not yet), so you have a lot of leeway which you should use to apply common sense and do the sensible thing.

Every object is responsible for itself

There is a concept more fundamental than object-oriented programming, and this is encapsulation. Encapsulation could be paraphrased as “every conceptual unit is responsible for itself”, where conceptual units can be of any scale (such as libraries, classes, methods, or even simple code blocks). Encapsulation is achieved by separating inner workings and implementation details from a public interface. It is really important to carefully choose what is part of the public interface, and what should be internal.

That part about methods and blocks also being eligible for encapsulation may be confusing, and I don't cover it in the rest of the post. It ends up meaning “declare variables in the narrowest possible scope, and don't use global variables”. This is not hypothetical. I have seen people return values from functions via global variables, and it was not pretty.

You shouldn't be able to reach invalid states

Object oriented programming is one popular strategy to make data responsible for themselves, by combining behaviour with these data. One crucially important responsibility is maintaining data consistency. That means a properly encapsulated object cannot be brought into an invalid state via the public interface, or conversely: everything that can be done via the public interface is valid. There are a number of steps to maintain consistency:

Don't allow inconsistent objects to be created in the first place. If necessary, use the builder pattern to describe temporarily inconsistent objects.

Don't allow data to be mutated in a way that makes them inconsistent.

Suggestion: Don't allow data to be mutated, at all.

Use static typing to prove consistency properties.

Use run-time validation to ensure consistency properties you cannot prove via the type system.

Static typing may seem like a no-brainer, but it's really important. When you declare fields or properties of an object, these usually have a specific type. If a certain field must contain a string, you can't put an integer there instead. The compiler then proves that your program is consistent with this requirement. However, all type systems are inherently limited, and cannot prove all properties of your program. E.g. in many languages null is a value of any reference type, and the type system often can't prove that a given variable, field, or return value will always be non-null. Furthermore, most type system lack means to statically describe types such as “a list with at least two elements” or “a floating-point number larger than or equal to zero”.

Such requirements should be described as far as possible using static typing; anything else has to be worked around via run-time validation. This validation is still the responsibility of any conceptual unit that wants to remain consistent.

Relaxing validation in trusted environments

In some cases, a component is only expected to be used from another trusted component (in C++ parlance: a friend). Then, defensive programming suggests that each conceptual unit should still be fully encapsulated. In practice, encapsulation is often relaxed for individual components and validation is skipped for “trused” data. If done so completely, this means that you only validate at the borders of your system. That system can still be encapsulated if and only if these privileged conceptual units are only reachable via a validation layer. In mainstream OOP languages this is done by making anything that doesn't have validation private or package-private, depending on where the validation border is.

Encapsulation vs. your scenario

Now we have learned a bit about maintaining consistency. How can we apply it to the scenario you outlined in your question? The basis is some object with two fields StartDate and EndDate with the constraint StartDate <= EndDate.

Shoot, I forgot StartDate/EndDate could be equal too and my code errors on half the data it tries to load from the database

This is great!

You were enforcing encapsulation.

You tested your code, which caught a mistake in your validation code. Thank God you tested it before using the code on a production database!

Ok so apparently the StartDate has to be set before the EndDate or my EndDate validation fails. Seems odd that I can't set properties like these in any order but ok.

This sounds like a problem with your validation code and not with validation in general. How could this problem be fixed? If StartDate == null is an illegal state, don't allow the object to get into that state. Think about using the builder pattern, proper validation in the constructor, and proper validation in the StartDate setter to enforce it's non-null. You could also disallow changing StartDate or EndDate once the object has been created.

But wait, unless I force the user to use a constructor with 10 parameters I can't absolutely ensure that there won't be any uninitialized properties because my validation logic will never get hit if they don't call the properties in the first place!

If your constructor has too many parameters, your object may be violating the Single Responsibility Principle. Otherwise, look into the builder pattern.

The constructor should always return an instance which is in a valid state. There is no excuse for doing otherwise.

Poop, I tried forcing the consumer to use ridiculously verbose constructors but now I'm having serialization headaches. The DataContractSerializer that WCF uses totally ignores my constructor. I'm sure there's a way around this though, I'll figure it out.

I am not familiar with the DataContractSerializer, but serializers generally bypass encapsulation. A solution is not serializing the object itself, but instead a dumb record that represents permanent state (memento pattern).

Uh oh, bad data has been imported into the database without going through my perfectly crafted domain model. Now my domain model prevents me from displaying this invalid data to the user so I have to correct it all myself. It would be great if I could jut allow them to correct it, but my domain model doesn't know how to do anything but crash when it reads invalid data.

The database is responsible itself for maintaining its data consistency (where “consistency” is meant in a slightly broader sense than in ACID). I previously talked about relaxing validation in a trusted context. It seems that here validation was relaxed without making sure that the database could only be reached through a validation layer, and therefore an unencapsulated system was created. The invalid data should have never been stored in the DB, and the user should have never been able to enter invalid data in the first place.

Anyway, isn't it great that you run tests with invalid data?


答:
OOP

When in doubt I follow 2 simple rules which help me make the right decision

Encapsulation and Information hiding

Low coupling and High cohesion

So this basically means Data + Behavior which you already know. But it also means that it is the class's responsibility to maintain the state of its instances, that is when you instantiate an object you should get a valid object with a valid state. These principles can be easily applied to modules and layers as well.

Validation

I can think of 2 different types of validation:

Data validation (aka Input validation)

Business Rules validation (your case)

As their names imply, unlike the former the latter should belong in the Domain Model containing all the business logic. Even if you use Factories and Builders to build your objects and carry out some validation there you still do it in the Domain Model. I liked the Input Validation vs. Business Rules Validation article on the subject.

Back to your question. Can [Business Rules] validation be considered as an object behavior? I would say it can but I tend to think of it as an act of maintaining an object's consistency. It's somewhat different from messages (Behavior) you send to objects in that validation is mostly hidden from the outer world and can't be triggered directly.

P.S. One way to solve your problem with "invalid" data is to have different models (CQRS) for read and write with the read model having looser requirements than that of the write model.

Title: OOP: Behavior + Data, but what about 'validation' behaviors?

Body:
EDIT: Thanks for all the great answers! In reading these responses I realized that I'm approaching this from the wrong angle so I wrote a new question here.

I had this discussion with my superior about whether validation rules should be in the domain model or not (specifically, in the property accessors) and I tend to lean towards putting them just about anywhere else but there. In my opinion, put them in the UI and in the brokers/persistence layer.

The argument in favor of putting it in the domain is to 'protect the data' because data is king and long after the application code has been replaced the data will still be there. And also because "object oriented programming is about coupling data and behavior".

So take, for example, an object that represents a scheduled item with a StartTime and EndTime and a validation rule that says the StartTime must be before the EndTime (and the EndTime must be after the StartTime). Then while programming this you repeatedly run into issues as you realize things like:

Shoot, I forgot StartDate/EndDate could be equal too and my code errors on half the data it tries to load from the database

Ok so apparently the StartDate has to be set before the EndDate or my EndDate validation fails. Seems odd that I can't set properties like these in any order but ok.

Or... I could add more code to check if the StartDate is null and allow the EndDate to be set to anything so long as StartDate hasn't been set yet. Ok I'll do that.

But wait, unless I force the user to use a constructor with 10 parameters I can't absolutely ensure that there won't be any uninitialized properties because my validation logic will never get hit if they don't call the properties in the first place!

Poop, I tried forcing the consumer to use ridiculously verbose constructors but now I'm having serialization headaches. The DataContractSerializer that WCF uses totally ignores my constructor. I'm sure there's a way around this though, I'll figure it out.

Except now I want to use Sql Sessions and by default it uses an XmlSerializer that requires a parameterless constructor.

Uh oh, bad data has been imported into the database without going through my perfectly crafted domain model. Now my domain model prevents me from displaying this invalid data to the user so I have to correct it all myself. It would be great if I could jut allow them to correct it, but my domain model doesn't know how to do anything but crash when it reads invalid data.

So here's what I'm trying to figure out: are 'validation rules' really 'behaviors'? Technically they are, but in regard to the idea that "object oriented programming is data + behavior", does this really apply to validation?


问:
Project configs for Java projects
How to store configs for project in Java. In normally case i stored it in 'src/main/resources/' with *.properties. How best approach for storing projects config for development, local, production environments?

I tried use *.prop with follow structure

```<code>resources
|_ config
   |_local
   |_development
   |_production
   |_environment.properties
</code>```

I want avoid it structure.

答:
In my humble opinion, the best approach here is to have an internal and external configuration.  The internal configuration contains all your defaults and will be contained in your resource folder.  The external configuration is a properties file deployed with your program that gets read afterwards and overrides any defaults.

For testing, it is nice since you already have everything you need to run the program without any additional configuration.  In production, you can override one or more values as you need to without rewriting the program.  See below for an example on how to load the configuration:

```<code>private static Properties getConfiguration() throws IOException {
    final Properties configProperties = new Properties();

    // Attempt to read internal configuration
    InputStream configStream = null;
    try {
        configStream = Main.class.getResourceAsStream("/configuration.properties");
        if(configStream != null) {
            configProperties.load(configStream);
        }
    } finally {
        if(configStream != null) {
            configStream.close();
        }
        configStream = null;
    }

    // Attempt to read external configuration (overriding as necessary)
    try {
        final File configFile = new File("configuration.properties");
        if(configFile.isFile()) {
            configStream = new FileInputStream(configFile);

            configProperties.load(configStream);
        }
    } finally {
        if(configStream != null) {
            configStream.close();
        }
    }
    return configProperties;
}
</code>```

Be sure to adjust the paths as necessary, though I personally prefer to keep the main configuration in an obvious spot both in my resources class path as well as externally.

Note that depending on the information contained in the configuration, you may want to purposefully exclude some information from your internal configuration.   An example might be information to connect to a database.  In such a case, when testing, you provide also the external configuration yourself that has all the missing database connection info.  When you deploy, you omit the external configuration and create a new one for your client (best practice dictates that you would check for the existence of these parameters for good measure, and throw an appropriate exception if missing).

Hope that helps!

Title: Project configs for Java projects

Body:
In my humble opinion, the best approach here is to have an internal and external configuration.  The internal configuration contains all your defaults and will be contained in your resource folder.  The external configuration is a properties file deployed with your program that gets read afterwards and overrides any defaults.

For testing, it is nice since you already have everything you need to run the program without any additional configuration.  In production, you can override one or more values as you need to without rewriting the program.  See below for an example on how to load the configuration:

private static Properties getConfiguration() throws IOException {
    final Properties configProperties = new Properties();

    // Attempt to read internal configuration
    InputStream configStream = null;
    try {
        configStream = Main.class.getResourceAsStream("/configuration.properties");
        if(configStream != null) {
            configProperties.load(configStream);
        }
    } finally {
        if(configStream != null) {
            configStream.close();
        }
        configStream = null;
    }

    // Attempt to read external configuration (overriding as necessary)
    try {
        final File configFile = new File("configuration.properties");
        if(configFile.isFile()) {
            configStream = new FileInputStream(configFile);

            configProperties.load(configStream);
        }
    } finally {
        if(configStream != null) {
            configStream.close();
        }
    }
    return configProperties;
}

Be sure to adjust the paths as necessary, though I personally prefer to keep the main configuration in an obvious spot both in my resources class path as well as externally.

Note that depending on the information contained in the configuration, you may want to purposefully exclude some information from your internal configuration.   An example might be information to connect to a database.  In such a case, when testing, you provide also the external configuration yourself that has all the missing database connection info.  When you deploy, you omit the external configuration and create a new one for your client (best practice dictates that you would check for the existence of these parameters for good measure, and throw an appropriate exception if missing).

Hope that helps!


问:
Spring web application deployment infrastructure
I'm interested in hearing out what's out there in terms of tips and tricks on deploying and maintaining a Java web application whilst keeping agile. I'm running solo on a startup project I'd like to maintain.

My tech stack is fairly simple:

Spring MVC

Spring Core for IOC (Inversion of Control)

JPA/Hibernate for transctional processing

all of this using a single instance of Tomcat as a container and MySQL to keep my states.

So my questions are:

How is it usually structured? I currently have three JAR/WAR projects:

the delegate [JAR] - containing my interfaces,

the implementation [JAR] - implementing my interfaces (above), and

the web application [WAR] - which is my Spring MVC web application depending on just the implementation

These are then wrapped into a WAR file which is then deployed to my Tomcat container. Is this recommended?

Is there a way to hot deploy? I've seen what Heroku does by making your project self-runnable (by including Jetty/Tomcat within the project itself), pulling the update via a git repository and reruns the project for you. I thought the usual modus operandi is running mvn package and move it to the container (which is already switched on).

答:
I would suggest you to take a look at Spring Boot. It can save you a lot of configuration. They have a lot of archtypes with different technology stack combinations out of the box.  Such app lightweight can be deployed anywhere. You can still switch from embedded Tomcat/Jetty to hosted alternative at later stage.

It is new opinionated way to build Spring based apps.


答:
One of the things I do is I try to avoid being put in a position where I get to decide where anything goes in the first place.  My initial interaction with GUI design was with Tcl/TK, which uses a very clever scheme of building the layout dynamically based on content (this is actually a model roughly reproduced in the CSS box model).  A line of text has a predetermined size, a button can guess it's size based on the text it contains, a box can guess its size from the number and size of the buttons it contains, and so on up to the toplevel window.

It does take some adjustment using this technique to make sure that things that should line up, do, but once you've done that, the layout suddenly becomes very fluid.  This is especially valuable when internationalizing the UI, since phrases which are longer in another language don't overrun their containers.

Since most things are on the web now, this principle still crudely applies, but CSS more or less expects you to make many subtle choices about how things are spaced.  I'll usually start off by building a rough interface with no CSS.  Then I'll start integrating any of the design mockups (from photoshop/illustrator/mspaint), and add the needed CSS to get the spacing where it needs to be.  "Where it needs to be" mostly means what is easy to read.  Nothing trumps readability here.

Title: Heuristics for absolutely-positioned GUI design - are multiples of 5 a good idea?

Body:
Disclaimer: I do not specialize in [desktop] GUI design, but have to do it on occasion. I have seen co-worker's dialogs worse than the once I created, and my major problem with them is that they can be unnecessarily big, and things do not line up.

To be more specific, I mostly do it in .Net Winforms, but occasionally with MFC(C++) as well. My simple heuristic so far is: I try to make the sizes and positions divisible by 10 ... or 5 if I have to. Something like a Label would be an exception, for it knows its own size. I find that things mostly look OK after I am done (of course there are other considerations such as grouping things intelligently, etc.), and I am satisfied because I know that every control has non-random position, and my OCD can now go back to sleep.

Somewhere at work I found a guide from MSFT about ideal spacing between things. Sorry, I do not have a source for it available. It has many rules, such as (for instance) 2 pixels between a button and a border, 3 pixels between two buttons horizontally, 4 pixels vertically, unless ... it is pretty complicated and not practical to remember. Additionally, I simply do not trust that MSFT knew much about GUI design, not until they hired an ex-apple person to help them design the ribbons for Office 2007, etc.

What rules/heuristics do you follow? References to short articles and other links are welcome.


问:
C++ returning references
Looking at making a GUI library for a game engine. I generally avoid pointers if I don't need them and in my below example I find that I don't and it works, but just curious if this design is generally considered good practice or if anyone has comments on it.

```<code>int main()
{
    // all widgets are positioned and sized according to the window size
    Window wndOptions("wndOptions");

    Button cmdExit("cmdExit");

    // the window doesn't own the widgets nor does it create the widgets so it's not responsible for deleting the widgets
    wndOptions.AddWidget(&cmdExit);

    // this is how you can find a control and get it casted also. make your variable a reference
    Button& test = wndOptions.FindWidget<Button>("cmdExit");

    test.SetPosition(50, 25);

    return 0;
}
</code>```

As you can see the idea is that you create your controls (button in this case) and pass a pointer to them to the Window. Then you can find the control by name returning a reference to that control in which you can manipulate the control. It's a bit pointless to use FindWidget() in this example since I have the cmdExit variable, but if I was to pass the window around this would be a way to find and use controls.

The biggest issue I have is that FindWidget() might not find a widget. Right now I throw an exception as not finding a control I would deem as a true exception and not something that should happen much if at all.

Any comments about the usage being done this way?

答:
Throwing an exception should mean that a piece of code somewhere catches the exception and handles it in an appropriate manner.

This might mean reporting the error back to the user to fix. Exceptions can be caused by transient situations where the handling mechanism is to try again later.

If it is a programming error that causes the widget not to be found, you might use an exception but an assert is likely to be preferable.

You would use shared_ptr if the widget does have more than one "owner" and clean-up depends on when the last reference is let go. Sometimes shared_ptr is also often used as a convenient way to store the items in a collection as it has the right semantics, even if, in a sense, the collection "owns" it.

If not finding something is a "normal" condition then you would have to return a pointer not a reference.

Title: C++ returning references


问:
TDD: how to test file outputs?
I'm really new to TDD, so I guess this question is pretty basic.

We're building a website, and part of the functionality is generating some files (binary files: Excel, PDF, whatever). How should I test this feature?

I've think about creating some static files and compare those with the generated ones, but a binary comparison isn't reliable (the files can have the same content but different checksums), and, if I understood TDD correctly, a logic comparison isn't a good idea, since I should use basically the same algorithm I use to generate the files, so I wouldn't be really testing anything.

How are this kind of things usually dealt with?

答:
Testing output files is always a difficult thing, same goes for testing downloading files from the web or output to the console.

One question you should ask yourself is: "How far can I test until I need the file?" Most of the logic can be tested by using some kind of replacement code, or simple text file generator.

Looking at your question you can generate multiple files, so I guess you already have some sort of separation between the code that provides the data and the code that is generating the file. So my answer will be based on the assumption that there is a kind of factory that generates the actual file.

A question you can ask yourself is: how complex is the factory, does it contains lots of extra logic or is only calling functions from another library that is creating the files for you?

If the factory does have lots of logic, is this the same for all kind of outputs or different for each output? When it is the same, you should think of refactoring it out of the factory, or add a format that is easy to test (like a plain text file).

When it only calls the a library, do you really have to test it automatically? aren't you going to test the library you are using?

So basically I would test as much as possible that doesn't require me to create a complex file. Plain text files, including html and json are relative easy to test because they are readable and comparable.
To test the binary outputs, I would probably generate a simple sample file to test against and write a test that uses the factory to generate the same file and test the file at byte level. Generated with the same parameters should generate the same file over and over again.

Title: TDD: how to test file outputs?


问:
Should private key files be checked-in in git?
In my understanding, git as version control system should track all resources or files that are necessary to build a software version.

If a private key file is needed for a server to function correctly (say to communicate with client that has the public key we distribute), then, should this private key file be tracked in git or somewhere else?

答:
I think it's better not, for security reason. Or everyone can access git can get the private key.

A better way may be to put private key and public key somewhere with internet access. Each client can get public key directly without authorization. And the server will get the private key with authorization. It's just a bit thought, since I'm not the export for the domain.

But if the private key kept in git is only for test but not real product, I think it's fine.

OwnerDisplayName: palazzo train

OwnerDisplayName: Landys


答:
As always, this is a non-obvious question only because there are several valid principles in conflict.

The one is that you should version-control everything that is needed to build the project. This is rather important. The other is that secret information should be passed out on a need-to-know basis to minimize the probability of data breaches. This can be extremely important or less important depending on what the consequences would be.

Since you know the circumstances of your organization better than we do, you must make the judgement call about that trade-off. We can only tell you how important things are in general.

Title: Should private key files be checked-in in git?

Body:
In my understanding, git as version control system should track all resources or files that are necessary to build a software version.

If a private key file is needed for a server to function correctly (say to communicate with client that has the public key we distribute), then, should this private key file be tracked in git or somewhere else?


答:
If the key is needed to build or run the software at all, then it is part of source and should be versioned. But I don't think that's common case.

If a key is needed to build or run the software, but the key is needed to designate the build as official release, then the key should live on the build server. In version control should be a method used for generating a valid key for testing or a particular key for use in testing. The key may be itself versioned, but not together with the project, because the team members don't actually need it, only the build server or the release manager do.


答:
No it should not.

A key has different specifications to source code or program.

The product should not work without a key

It is specification of product that it does not work without a key. If you include the key in the distribution you effectively destroy its use.

A key should be easily replaceable.

 In fact, sometimes it's needed to regularly replace it. And sometimes a deploy of a new version is a difficult and long process. Combine that with the need to rebuild your project to get a new key, and you have the recipe for a perpetual headache. If you do not require a rebuild to get the new key, then there is no reason to put the key into git - it's not used in building, bundling or testing your app.

Consider code audits.

An auditor needs to have access to source code to verify logic (and sometimes to a working program). They are not supposed to see (and hence be able to memorize) your private keys. I'm not going to go through whether it's realistic to memorize a 2048-bit key by glancing at it - sometimes reviews are done remotely.

A key does not need a history.

A key is not tied to the version of the software in most cases. Key change dates and reasons may be interesting, but those do not need to be available to everyone.

Keys are issued per company or per server, not per application.

Should you ever decide that you need a second server in another country with different laws and a different key, or allow a different company to run your server software as well, this is most important. Those should have different keys. Bundling your key with the app is a no-go then.

Keys should not be public information

Does your intern really need to have access to your production server key? Really? Does your compliance/security department concur?

There is but one key that you may want to include in Git - a test key for an internal test server or a local server. That will ease initial deployment and allow you to change key formats without making a company wide email asking all devs to change their local keys as well, while not invalidating the actual security and integrity of your production server.


答:
If you put a private key it git, it is no longer private. If you don't mind that happening, then do it. If you want to keep the private key private, don't publish it on a public server.

Instead, check in to git instructions on how someone can generate and use their own private key.


问:
If we have TDD and BDD why do we need QA for?
If we have TDD and BDD why do we need QA for? Isn't the job of the developer to write bugs or failing tests? If this is true how a QA fit in? Thanks.

答:
automated testing scripts help with logic and clicking around the application to ensure its all connecting nicely.

What it doesnt account for is:

has the automated script checked for all the features created?
does it check the logic properly?

Lastly:
The layout of the design is not checked here. Testers with keen eyes for detail are very helpful to catch lots of little things in the UI experience between different screen sizes, platforms, and devices. Also more eyeballs on the software checking things tends to improve logic flow for a better UI experience with less confusion.

OwnerDisplayName: Labanino


答:
It's certainly arguable that you do not need "QA", though that depends on what you mean by "QA". Do you need a separate QA team or department? Probably not. Do you need trained QA professionals? Probably so.

Testing is a skill, and it is typically not a skill that most developers have. Every team should have trained, professional testers. Their job should be to make sure the software is well tested by both working with the developers to write good tests during development, and to perform their own testing such as end-to-end exploratory testing.

As an analogy, think about a building inspector. For example, if a carpenter checks that the roof they built isn't leaking, why have a building inspector? Do you just take the word of the carpenter? You still need a building inspector because they know the common mistakes that are made and how to spot them.

So, even if you have a development team that conscientiously does TDD, ATDD, BDD, or one of its variants, you still need trained testers to insure you have well tested software.

Body: If we have TDD and BDD why do we need QA for? Isn't the job of the developer to write bugs or failing tests? If this is true how a QA fit in? Thanks.

OwnerDisplayName: Bryan Oakley


答:
TDD is a design tool used by developers, it is more about design than tests and verifications.

BDD is a communication tool to bridge the gap between developers, QA , Product owners or business analysts. BDD makes sure we share the same vision of what need being built using concrete examples instead of relying on an abstract specification.

QA is a role with the responsibility of verification testing around features, security, performance, compliance so on...QA can also be responsible for providing test automation tools.

So as you can see they are three orthogonal things (In a three dimensional space of course).

Title: If we have TDD and BDD why do we need QA for?

OwnerDisplayName: sigo


答:
You wrote "If this is true how a QA fit in?" which implies you are talking about a person responsible for QA. I'll get back to that in the end of the answer.

Quality assurance and quality control are two very distinct concepts. I believe when we as developers talk about QA we most often refer to the people either creating the tests, or executing them, or both. For me, quality assurance is the systematic planning and documentation of quality related activities. Most often documented in an overall quality system. We do that to provide some sort of "assurance" that we care (in plain English). Quality control, to put it simple, is activities related to the verification that we are following the plan.

So when you ask this question you need to put TDD, BDD (or any other practice, methodology, technique, etc.) in the right category. You also have to figure out what you actually mean with QA.

Blunt; Just because someone is doing TDD it doesn't mean that there will be quality. It also doesn't mean that even if someone is good at doing TDD it will be enough coverage. Also the quality system would include criteria for how much testing would be enough, and it can often be as simple as "test what needs to be tested". But in a real quality system that definition wouldn't be able to stand on its own of course. You need to be able to judge this from as unbiased position as humanly possible.

I think there is often a misconception that QA/QC needs document requirement, tests, etc. I often have to argue (with our QA) that quality is not created by the process itself. Quality needs to exist in development, and the role of the process is to collect sufficient evidence to prove that you have quality. That means that QA from the perspective of "having a plan" is actually more important to me than quality control. And that is where TDD and BDD plays a role as activities and practices we practice to assure quality output of our work.

A QA as you write it, like it is a specific person you are thinking about, probably mean what we usually label as QAE (engineering). That is basically the art and business of creating material for verification and validating the result of coding. And it is truly an art. A person/department doing QAE usually do a lot more than testing the system individually, since verification and validation activities usually stretches far beyond basic BDD/TDD.
But from a pure "coders perspective" I tend to look at this as a responsibility. And then it depends highly on the organization structure, size, business, etc. if that responsibility is connected to a role (or several).

I would strongly argue that regardless how and what you do, you always need, and always have QA. You always have QC. You always have QAE. It's just that in small teams this might not be an explicit resource, role or organisation.

So what is the role of TDD in all this? Well, to me it could have no role at all, or mean everything. TDD to me is an approach to writing code, not writing tests. People seems to argue about things like "is London style better than Chicago or even Piteå style". I would argue that Piteå style always win, since that is my style. And Piteå style mean that most of the time after writing something extreme TDD style I end up with everything from functional, integration, unit, black-box, white-box. The only thing I can say for sure is that from TDD Piteå style I always end up with much simpler, more to the point, more covered, better building .. code. Piteå style also mandate that it is perfectly OK to not produce any code at all if quality so dictates. Occasionally Piteå style mandate a beer or several, but that is a different kind of quality assurance.
In Piteå Quality System TDD is the foundation I build my assurance that what I produce will be of sufficient quality, and being able to maintain it later. And my CI server is tireless and continuously controlling that I don't slip up.

But ultimately, as far as real quality goes, only the users of my code can bare witness. I can only assure them that I do quality at the best of my ability. Quality first, always, then TDD.

[Piteå is my hometown]

OwnerDisplayName: gurun


答:
Developers are very, very good at abstraction. If you give us half a problem, we'll come up with the whole solution. In fact, we're so good at this, we won't even notice that we've only got half the problem. We're "solution space" people. Our job is to solve problems.

Testers, on the other hand, are "problem space" people. They're the ones who ask, "What about X? Or Y? Have you thought about Z?" They know how to break our code before we've even written it. If we're really nice to them, they'll tell us. Their job is to understand the problem backwards.

An analyst or SME might be good at working out which problems are the most important to solve, but once they've made that decision, testers are just as good as they are at understanding the nature of the problem chosen. Devs tend not to be good at this because of our "solution space" heads; we blind ourselves to the things we don't know.

In an environment where you're doing BDD or TDD, testers are invaluable for helping you, and the business, spot the tests or scenarios that you've missed. They're also great for doing exploratory testing, so they find the things that automated tests can't (for instance, one of my favourite testers spotted that I'd put an SQL call in the wrong place and that a particular behaviour was making 10 calls to the DB where it only needed to do 1).

I tend to refer to "tester" these days rather than "QA", since assuring quality is indeed, as gurun said, more than just one person and a bit of process.

OwnerDisplayName: Lunivore


问:
Why should your code not use 100% CPU?
I'm speaking specifically about a C# .NET 4 program running on Windows XP or higher, but general answers are also acceptable.

Assume an already optimized and efficient program. The problem here is entirely down to effects of high CPU usage on hardware, and whether a high-usage program should be throttled to reduce wear, not on whether my implementation is efficient.

A colleague today suggested that I should not aim for 100% CPU utilization on my data load processes because "modern CPUs are cheap and will degrade quickly at 100% CPU".

Is this true? And if so, why? I was previously under the impression that 100% CPU usage was preferable for an intensive or long operation, and I couldn't find any respectable sources on the subject either way.

答:
If cooling is insufficient, the CPU might overheat. But they all (well, at least all modern PC CPUs) feature various thermal protection mechanisms which will throttle the clock speed or, as a final resort, shut down.

So yes, on a dusty laptop, 100 % CPU load could cause temporary problems, but nothing will break or "degrade" (whatever that means).

For CPU bound problems, 100 % CPU load is the right way to go.

As for application (UI) responsiveness, that's a separate concept from CPU utilization. It's entirely possible to have an unresponsive application that uses 1 % CPU, or responsive application that uses 100 % CPU. UI responsiveness boils down to amount of work done in the UI thread, and the priority of UI thread vs. other threads.

Title: Why should your code not use 100% CPU?


答: If you want to go the "fixed spacing" way, multibles of 10 are ok. Switching down to multiples of 5 is only necessary when you run out of screen real estate. In one company I'm working for, we use a framework where multiples of 10 are the default setting in the (homegrown) GUI editor. Only in very rare occasions someone has to change that. The resulting forms are not exactly aspirants for the beauty contest, but nobody has complained, either.</p>


问:
Find n nodes farthest away from each other
I'm looking for an algorithm that gives me the n nodes that are the farthest away from each other.

Can this be accomplished relatively efficiently?

To clarify my question:
I think of the problem as a variant of the opposite of the travelling salesman problem. We have this graph:

The distance matrix looks like this:

```<code>    a   b   c   d   e   f
a   0   184 222 177 216 231
b   184 0   45  123 128 200
c   222 45  0   129 121 203
d   177 123 129 0   46  83
e   216 128 121 46  0   83
f   231 200 203 83  83  0
</code>```

For example, the salesman needs to visit any 4 nodes shown above. He must be on the road between all nodes he visits as long as possible. Which nodes would he visit?

My guess is we're looking for the 4 nodes with the maximum average distance between them. Is there a reasonably efficient, preferably non-exponential, way to do this? What if I don't need an exact solution to the problem?

答:
To find the four longest distances, you need to search over all the distances. So for n nodes, you need to loop through n^2 distances, and so something like:

```<code>if dist > smallest_max
  replace smallest max in array of four maximums with dist
  recalculate the smallest max from array
</code>```

This is O(n^2), which is not good but it's not exponential like traveling salesman.

Body:
To find the four longest distances, you need to search over all the distances. So for n nodes, you need to loop through n^2 distances, and so something like:

if dist > smallest_max
  replace smallest max in array of four maximums with dist
  recalculate the smallest max from array

This is O(n^2), which is not good but it's not exponential like traveling salesman.


答:
If you are running your code on clients, 100% CPU utilization means that client computers in that time cannot be used for anything else but tasks with higher priority. As most applications usually run in default priority, users using those computers will notice computer freezing and will be unable to do ought else on their computers.
Even if we are talking about short bursts, users working on something will still notice it.

As others said, you were pretty secretive about the setup, so I cannot say for sure. But, if your clients are desktop computers, stay away from 100% CPU utilization. Not because of CPU degradation, but because it is not good form to disrupt users during their work.

Title: Why should your code not use 100% CPU?

Body:
I'm speaking specifically about a C# .NET 4 program running on Windows XP or higher, but general answers are also acceptable.

Assume an already optimized and efficient program. The problem here is entirely down to effects of high CPU usage on hardware, and whether a high-usage program should be throttled to reduce wear, not on whether my implementation is efficient.

A colleague today suggested that I should not aim for 100% CPU utilization on my data load processes because "modern CPUs are cheap and will degrade quickly at 100% CPU".

Is this true? And if so, why? I was previously under the impression that 100% CPU usage was preferable for an intensive or long operation, and I couldn't find any respectable sources on the subject either way.


答:
Windows programs (winforms/WPF) should at all times stay responsive.
With a naive implementation of a process that uses 100% cpu resources it's all too easy to make your program or even your system seem sluggish and hanging.

With a good implementation (for instance: use a seperate thread with lower priority) it shouldn't be a problem.

You shouldn't worry about your cpu breaking sooner.

Title: Why should your code not use 100% CPU?


问:
How to compare two different hashset objects with more than 100,000 records
I have two classes

```<code>class A{
  int id;
  String name;
  public boolean equals(Object o)
  {
     if(o instanceof A) {
           A a=(A)o;
           if(a.getId().equals(this.getId()))
              return true;
       }
    return false;
  }
  public int hashCode() { return id;}
  //setter& getter
}

class B{
  int id;
  String address;
  public boolean equals(Object o){
    if(o instanceof B)
    {
      B b=(B)o;
      if(b.getId().equals(this.getId()))
       return true;
    }
    return false;
 }
 public int hashCode()
 { return id;}
 //setter& getter
}
</code>```

I have 100,000 A type objects and 100,000 B type objects.

So that, I have eliminated duplicates in both classes using HashSet.
Now i am comparing HashSet and HashSet with id field and place matched objects in another list with following code in main class..

```<code>HashSet<A> A_Set=new HashSet<>();
HashSet<B> B_Set=new HashSet<>();
    for (A c1 : A_Set) {
            for (B c2 : B_Set) {
                if (c1.getId().equals(c2.getIid())) {
                    matchedData.add(c1);
                }
            }
        }
</code>```

the above code taking 15 minutes to compare 100,000 records...Is there any solution to increase performance of code.. (with in less time)

答:
You have two sets as and bs. You want to calculate the set cs such that it contains all the elements from set A which have an ID which is the same as that of any object in set cs. You are currently using this nested loop:

```<code>Set<A> as = ...;
Set<B> bs = ...;

Set<A> cs = new HashSet<>();

for (A a : as) {
    for (B b : bs) {
        if (a.getId() == b.getId())
            cs.add(a);
    }
}
</code>```

This takes quite long because you loop through all elements of the set bs. It has algorithmic complexity O(|as| · |bs|), where |x| is the size of set x.

We could apply one simple optimization: Once we've found a matching element in set bs, we add the current a to cs and continue with the next element from as. We do not search for further matches in bs, as adding a matching element again doesn't change the result set:

```<code>for (A a : as) {
    for (B b : bs) {
        if (a.getId() == b.getId()) {
            cs.add(a);
            break;
        }
    }
}
</code>```

While this should be quite a bit faster, this still has O(|as| · |xs|) complexity.

We can do better. For example, we could sort all elements by their ID (a one-time O(n log n) cost) in ascending order, and iterate over them using an O(n) algorithm that skips elements as long as they are larger than the current element from the other sequence. This is better, but still not optimal.

The optimal solution is to create a hash set of IDs of the bs set. This does not require sorting of both sets, and allows linear-time membership test. There is a one-time O(n) cost to assemble the set of IDs.

```<code>HashSet<Integer> bIds = new HashSet<>(bs.size());
for (B b : bs)
    bIDs.add(b.getId());

for (A a : as)
    if (bIds.contains(a.getId()))
        cs.add(a);
</code>```

The total complexity of this solution is O(|as| + |bs|). In other words, this should run roughly 100,000 times faster.

Body:
You have two sets as and bs. You want to calculate the set cs such that it contains all the elements from set A which have an ID which is the same as that of any object in set cs. You are currently using this nested loop:

Set<A> as = ...;
Set<B> bs = ...;

Set<A> cs = new HashSet<>();

for (A a : as) {
    for (B b : bs) {
        if (a.getId() == b.getId())
            cs.add(a);
    }
}

This takes quite long because you loop through all elements of the set bs. It has algorithmic complexity O(|as| · |bs|), where |x| is the size of set x.

We could apply one simple optimization: Once we've found a matching element in set bs, we add the current a to cs and continue with the next element from as. We do not search for further matches in bs, as adding a matching element again doesn't change the result set:

for (A a : as) {
    for (B b : bs) {
        if (a.getId() == b.getId()) {
            cs.add(a);
            break;
        }
    }
}

While this should be quite a bit faster, this still has O(|as| · |xs|) complexity.

We can do better. For example, we could sort all elements by their ID (a one-time O(n log n) cost) in ascending order, and iterate over them using an O(n) algorithm that skips elements as long as they are larger than the current element from the other sequence. This is better, but still not optimal.

The optimal solution is to create a hash set of IDs of the bs set. This does not require sorting of both sets, and allows linear-time membership test. There is a one-time O(n) cost to assemble the set of IDs.

HashSet<Integer> bIds = new HashSet<>(bs.size());
for (B b : bs)
    bIDs.add(b.getId());

for (A a : as)
    if (bIds.contains(a.getId()))
        cs.add(a);

The total complexity of this solution is O(|as| + |bs|). In other words, this should run roughly 100,000 times faster.


答: If you can, make your code a lower priority task, and make sure to keep the CPU-heavy thread separate from the GUI. Then you might have 100% utilization, but the user can always still run other tasks and stay responsive. By itself, a CPU is designed to stay running at 100% usage for a while, or it would not get released. Unless the end user has made serious and dangerous modifications to their hardware, you can't damage anything.</p>

Title: Why should your code not use 100% CPU?


问:
Is objective-C++ being phased out?
Is apple phasing out support for objective-c++?  Note the following:

In the Objective-C language manual, there used to be a section on mixing objective-c and c++.  That section is now missing.

Links to articles on objective-c++ on the apple developer website seem to be broken, and are now redirected, e.g. this one, which I found on this stackoverflow question.

Searching for c++ on the apple dev website brings very little in the way of current information.

Should I be concerned about using c++ for iOS development?

答:
Absolutely the answer is no. Much of the Objective-C runtime and many private parts of public frameworks and private frameworks powering Apple software are written in Objective-C++ today and that will not likely change.

They use it to take advantage of existing open source software libraries as well as the STL where it makes sense. Clang is written in C++

Oh and all of IOKit is C++

Xcode is in many parts written in Objective-C++

C++ for the things it makes sense for, Objective-C for the API and the UI.
(in other words, expose a great stable API that is plumbed with C++ where it makes sense)

Title: Is objective-C++ being phased out?


问:
How do you plan releases with new features in a development / releases branch model?
We are trying to implement a branch model in Mercurial.

We have read the "Successful GIT branching model" and I proposed another, based on branched version numbers.

Then I ended accepting the model with 2 long lived branches, development and releases.

One thing I like about it is the possibility to do "nightly builds", but I am concerned about how to plan major features for versions.

How is this "development" branch supposed to work? Should get fixes here as fast as I can, but only merge features whenever I want? How do you do this?

I want to plan like this:

Version 1.3:    CKEditor + Vote Comments

Version 1.4:    Delete and restore comments

And I want this to be in the roadmap of Redmine, which means belonging to a version number before the feature is fully programmed. Mostly because I want to show me (customers in the future) that there is indeed a plan.

答:
Features should be merged into the development branch whenever they are ready. This should happen as soon as possible in order to keep all branches fairly consistent, which reduces merge conflicts. Once merged, feature branches can be deleted. Big features can be split into a number of smaller features. Long-running feature branches can be kept in sync by periodically merging the development branch into feature branches.

A release could be made whenever you have added a new user-visible feature, or when all planned features for the next release have been merged into the development branch, depending on your release model. This lends itself very well to agile-ish approaches where you decide on the next handful of features for the next near-future release. Once you've shipped, you re-evaluate priorities and determine the next set of features.

If you do have a roadmap that reaches further into the future than the next release, this does not impact a Git-Flow like branching model: you complete the features for the first milestone, then release it. You complete the features for the second milestone, then release it. If you complete features planned for the second milestone before the first milestone has shipped, these features will be present in the first release. E.g. browser vendors do this all the time with experimental features that are not activated by default.


问:
Extension in use case diagram: Library management example?
I have problem to understand the extension relation in the use case diagrams, sometimes some relations seem extension.

For example in the library system, what is the relation between borrowing a book use case and reservation a book use case?

Could the reservation be the extend of borrow?

Scenario of Reserve a book:

Member refers to the librarian

Gives the information of the book

Librarian record the book in the reservation list  for the member

Scenario of Borrow a book:

Member refers to the librarian

Gives the information of the book

Librarian lend the book if it's available

Librarian reserve the book for the member if it's not available

In general what are rules of thumb to find out extension relation?

答:
I happen to come across this lately while studying about OO design.

I have problem to understand the extension relation in the use case
  diagrams, sometimes some relations seem extension.

There is an extension relationship if one use case extends the behavior of another. The former is the extension, and the latter is the base. In extend relationships, the base is independent and meaningful by itself. This is not the case for the extension--it depends on the base. It does not stand on its own.

In general what are rules of thumb to find out extension relation?

Use an extension relation when one use case has behavior that is optional, or when it has a behavior that executes only under some conditions.

Could the reservation be the extend of borrow?

If a member can make a reservation independently (for whatever reason) even if the book is available (like he reached his borrowing limit), then no, reservation cannot be the extend of borrow. Reserve can stand on its own. A member can make a reservation without having to borrow. Otherwise, yes, it is an extension of borrow because it executes only when borrowing a book that is unavailable. I hope this helps.

Oh, and in the case that reserve is an extension of borrow, don't draw it like you did in your diagram. To show extend relationship, the extension connects to the base with an open arrow. Add the keyword extend. The arrow points from the extension to the base.


问:
Is it possible/good idea to reduce chance of crashing by catching Error?
I have a class the implements A which will run a certain method of class B. There is a requirement that this A should never crash when running this operation (which is not possible, right?).

To reduce the chance of crashing I'm catching Throwable around the operation, like so:

```<code>public void method(B b)
{
    try
    {
        b.operation
    }
    catch(Throwable e)
    {
        //Log e
        //Clean up stuff
    }
}
</code>```

My questions are:

Would this actually help in reducing crashes caused by any thrown Error?

Is it a good idea to ever catch an Error?

答:
In general, you should NEVER catch things like Exception, Throwable, or Error, but only those specific subclasses of those that your application can reasonably be expected to handle and survive (or at least log something useful about before crashing).

Exception handling is supposed to be just that, handling error conditions and dealing with them in such a way that the application can continue running or report what happened before terminating.

It's not meant to be error masking, hiding problems and then just try to continue as if nothing happened. Not only will it rarely work (it will rear its ugly head somewhere else in the application soon, making the problem worse as now you have even more corruption in your state and/or data, but you now have a problem that's that much harder to track down and debug, and eventually fix.


答:
You have some very good comprehensive answers.  I'll just address your specific use case.

If you have two or more attributes that depend on each other then don't have individual setters and validators. As your question shows, you can get into all edge cases where one attribute is changed but not the other.

Instead, make a value object called ScheduledTimes, feed start and stop into it's constructor, validate within the constructor and then add it to your scheduled item.  If the times need to be changed then replace it with a new value object.


答:
"..modern CPUs are cheap and will degrade quickly at 100% CPU".

You don't have to worry about "CPU degradation" at all. Modern CPUs are not of less quality than in former times.

It is very expensive (and is getting more expensive every couple of years) to make CPUs, some billions to build a new fab are not uncommon (see link).

http://en.wikipedia.org/wiki/Semiconductor_fabrication_plant

The production costs of a CPU depends at most on the no. of units produced. This is a well known fact in economy. That's the reason they can be sold (relatively) "cheap" after all.
(I think, no link necessary here)

I can list a number of reasons why I would consider modern CPUs to tend to be of more quality than in "former times".

But only the most important: Advantages in testing. Modern electronics are "designed for test". Whether software or hardware, the broad insight of valuing tests over nearly everything else, is not so old.
For CPUs, the tests are even taken for forming the different price and frequency types, e.g. the best CPUs are sold with highest frequencies. Despite that, the cheaper processors are very often able to operate with higher frequency than sold- they are crippled only for the reason that the manufacturer wants to sell some "high level" processors with higher prices.

(One the other hand, of course there are more errors possible for a processor with more than 1.5 billion transistors as normal nowadays than with some thousand transistors of a processor of the seventies. But this does not contradict to my answer IMO. Processors in general tend to have many known errors, at least in microcode, but this is not subject here.)

There are even more reasons not to worry about CPU degredation for your program:

First reason is that modern CPUs decrease their frequency or throttle, if they are getting too hot.

It should be clear that if you utilize the CPU 100% 24/7 the whole year it will normally die earlier than a CPU only used every second week one hour. But that is true for cars, too, by the way. Only in such cases I would think about CPU utilization and potential sleeps yourself.

Second reason is that it is really very hard to write a program which uses 100% of the CPU from OS, (e.g. in Windows). Besides, modern CPUs (normally) have at least 2-4 cores. So a traditional algorithm which tends to use 100% of a single core CPU, now has only 50% on a dual core CPU (simplified but seen in real scenarios).

Moreover the operating system has the control over the CPU and not your program, so if there are other applications with same or higher priority (what is the default), your program is only getting as much CPU as possible, but the other applications will not starve. (Of course this is only the simplified theory, and of course the multitasking of Windows, Linux and others is not perfect, but overall I would consider that for true).

"I was previously under the impression that 100% CPU usage was
preferable for an intensive or long operation.."

Yes, stay with this. But for example, if you do waiting&looping for another process, in other words doing nothing, it would be not too bad if you Thread.Sleep() some milliseconds in that loop, giving extra time to others.
Whereas it is not necessary for a good multitasking OS, I solved some issues with this e.g. for Windows 2000. (That does NOT mean of course to use Sleep() in calculations for example..

Title: Why should your code not use 100% CPU?


答:
File output usually belongs to integration-tests(=having some components working together) and not to unittests(=test one component in isolation)

if your pdf-generation is implemented in a way that the same input always produces the same output you can try approvaltests which does a binary compare to the previous call result. if there is no previous result or the binary compare  is different a gui asks you if old and new version are the same showing you both pdf files with acrobat reader.

This way you are informed every time the output changes which might be ok or not.
Example

note:

if the pdf-generation inserts the current date into the output then the ouput will be different on every call.

If you provide the date as a parameter to the pdf-api then you can generate identical output.

Title: TDD: how to test file outputs?

Body:
I'm really new to TDD, so I guess this question is pretty basic.

We're building a website, and part of the functionality is generating some files (binary files: Excel, PDF, whatever). How should I test this feature?

I've think about creating some static files and compare those with the generated ones, but a binary comparison isn't reliable (the files can have the same content but different checksums), and, if I understood TDD correctly, a logic comparison isn't a good idea, since I should use basically the same algorithm I use to generate the files, so I wouldn't be really testing anything.

How are this kind of things usually dealt with?


答:
There are two relationships in a use case diagram - include and extend.

The extend relationship is used when one use case adds behavior to another use case. In this situation, the base case would be executed. Then, depending on what happens during execution of that one use case, one or more other use cases could possibly be executed. Note that it's not required that an extension actually be executed - it's just a possibility. This also indicates some level of reuse between the features.

The include relationship is used when one use case includes the functionality of another use case. The specific behavior is not important, but the end result is, which means that the included use case could have a different implementation, but the same steps and end result. In this type of relationship, the included use case is usually not available as a stand-alone use case.

Looking at your particular example, I developed two use case models that I feel are more appropriate. In both, I changed the actor from "Member" to "Librarian". It appears that the person actually interacting with the software is not the library member, but the librarian.

In this example, the Librarian can perform two functions - check out a book or reserve a book. Both examples require the librarian to look up the book using the information provided by the member. However, the search functionality is not available as a stand-alone entity. I'm not sure that this is what you are going for.

In this example, the Librarian can perform three functions - looking up books, checking out books, and recording reservations. Both checking out books and recording reservations use the look up book use case, but add additional behaviors. The implementation details are left as an exercise for additional specification, but this indicates that the in order to either check out a book or place a reservation, the librarian must first look up the book. I believe this is more in line with the functionality you are describing in your question.

Title: Extension in use case diagram: Library management example?

Body:
I have problem to understand the extension relation in the use case diagrams, sometimes some relations seem extension.

For example in the library system, what is the relation between borrowing a book use case and reservation a book use case?

Could the reservation be the extend of borrow?

Scenario of Reserve a book:

Member refers to the librarian

Gives the information of the book

Librarian record the book in the reservation list  for the member

Scenario of Borrow a book:

Member refers to the librarian

Gives the information of the book

Librarian lend the book if it's available

Librarian reserve the book for the member if it's not available

In general what are rules of thumb to find out extension relation?


问:
Why is having merge bubbles in your git history not actually that bad?
In the past year, most of the rest of my group (of engineers that I work with), has ended up deciding that merge bubbles really aren't that bad.

At the very least, I'm seeing that other developers do not consider rebasing worth the effort needed to avoid merge bubbles when merging (sometimes very badly structured) pull requests.

Why is it actually not that bad to have merge bubbles in your commit history?

To be clear: I am not asking if merge bubbles are bad or not! I am asking why they are not bad.

答:
First of all, as you already pointed out, they require less work.  In my opinion, the burden is on the process that requires more work—in this case the rebase process—to prove its superior utility.

The biggest argument is that merges preserve an accurate history, as the development actually happened.  A linear, consolidated history is useful at a higher level of abstraction, such as the quality and release teams.  It's quite the opposite on a development team, where it's extremely useful to know exactly when and how a bug was introduced.  Did it happen because of a merge, or was the bug there during development and I just missed it?  If the history gets destroyed, you have no way to answer questions like that.

The other reason is it encourages fluid cooperation in other than star topologies.  In centralized version control, the only way to share your work is to commit it to the central server.  With distributed, you might have two people working together for a day or two, pulling from each other, then they push to the central server once it's ready for the larger group.  That's a very efficient and natural way to want to work.

If developers have to worry about if x rebased commit contains the same changes as y commit they pulled from someone else during active development, that creates a cognitive load that discourages that mode of cooperation.  Doing merges offloads that tracking effort to the version control software, which is why we have it.


问:
Prime symbol in Python variable name
So I'm a terrible person and I want to name a variable in my mathy-python3 code s′ (that's U+2032 PRIME).

I was under the impression Unicode literals work as identifiers in Python 3, which is why my ɣ, α, and ε's are working fine.

Is the prime symbol specifically forbidden because of how terrible it would be to use?

答:
You cannot just use any Unicode character in Python identifiers. There are rules governing what can be used:

```<code>identifier   ::=  xid_start xid_continue*
id_start     ::=  <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
id_continue  ::=  <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
xid_start    ::=  <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">
xid_continue ::=  <all characters in id_continue whose NFKC normalization is in "id_continue*">
</code>```

The Unicode category codes mentioned above stand for:

Lu - uppercase letters

Ll - lowercase letters

Lt - titlecase letters

Lm - modifier letters

Lo - other letters

Nl - letter numbers

Mn - nonspacing marks

Mc - spacing combining marks

Nd - decimal numbers

Pc - connector punctuations

Other_ID_Start - explicit list of characters in PropList.txt to support backwards compatibility

Other_ID_Continue - likewise

The above is the Unicode equivalent to any number of letters, digits and underscores, as long as you don't start with a digit.

The U+2032 PRIME codepoint doesn't fall in any of those classes; it is considered Po - other punctuation instead.

I've linked the Unicode categories to codepoint.net queries for you so you can see what kind of characters are permitted. Your other identifier choices are all Ll lowercase letter characters, by the way.

You do want to be careful and use some common sense in what you use as identifiers. Keep them readable and recognisable. Preferably they should be easy to type too, so personally I'd steer away from using greek lowercase letters myself. I'd rather use alpha, gamma, epsilon and s_prime instead here.

ContentLicense: CC BY-SA 4.0

Title: Prime symbol in Python variable name

Body:
You cannot just use any Unicode character in Python identifiers. There are rules governing what can be used:

identifier   ::=  xid_start xid_continue*
id_start     ::=  <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
id_continue  ::=  <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
xid_start    ::=  <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">
xid_continue ::=  <all characters in id_continue whose NFKC normalization is in "id_continue*">

The Unicode category codes mentioned above stand for:

Lu - uppercase letters

Ll - lowercase letters

Lt - titlecase letters

Lm - modifier letters

Lo - other letters

Nl - letter numbers

Mn - nonspacing marks

Mc - spacing combining marks

Nd - decimal numbers

Pc - connector punctuations

Other_ID_Start - explicit list of characters in PropList.txt to support backwards compatibility

Other_ID_Continue - likewise

The above is the Unicode equivalent to any number of letters, digits and underscores, as long as you don't start with a digit.

The U+2032 PRIME codepoint doesn't fall in any of those classes; it is considered Po - other punctuation instead.

I've linked the Unicode categories to codepoint.net queries for you so you can see what kind of characters are permitted. Your other identifier choices are all Ll lowercase letter characters, by the way.

You do want to be careful and use some common sense in what you use as identifiers. Keep them readable and recognisable. Preferably they should be easy to type too, so personally I'd steer away from using greek lowercase letters myself. I'd rather use alpha, gamma, epsilon and s_prime instead here.


答: It looks like a single-quote character, which is probably what most programmers would simply assume, unless you told them, or they squinted and looked really close. Heck, there could be fonts that use the same glyph for both characters. Even if you can use it, I'd avoid it, to avoid the possible confusion it might cause.

Title: Prime symbol in Python variable name

Body:
So I'm a terrible person and I want to name a variable in my mathy-python3 code s′ (that's U+2032 PRIME).

I was under the impression Unicode literals work as identifiers in Python 3, which is why my ɣ, α, and ε's are working fine.

Is the prime symbol specifically forbidden because of how terrible it would be to use?


答:
The reason merge bubbles are considered bad in the first place is that they mess up the history log. When it's only one bubble per segment it's not that bad - but when a large team uses merge all the time the history graph starts looking like one of these follow-the-line mazes.

If your team decided that merge bubbles are not so bad, than either:

They are willing to accept the messy history graph

They are willing to use flags like --first-parent to make it look linear

The team is not big enough for this to go out of hand(not likely)

Any other reason that allows you to comply with messy history graphs

Title: Why is having merge bubbles in your git history not actually that bad?

Body:
In the past year, most of the rest of my group (of engineers that I work with), has ended up deciding that merge bubbles really aren't that bad.

At the very least, I'm seeing that other developers do not consider rebasing worth the effort needed to avoid merge bubbles when merging (sometimes very badly structured) pull requests.

Why is it actually not that bad to have merge bubbles in your commit history?

To be clear: I am not asking if merge bubbles are bad or not! I am asking why they are not bad.


答:
"modern CPUs are cheap and will degrade quickly at 100% CPU".

I don't think anyone's actually addressed the "degrade" part of this question. ICs will degrade when the die temperature exceeds the manufacturer's limits. ICs are usually designed to operate up to 125C, although every 10C increase shortens life by 50%

Processors didn't always have thermal regulation. Then some AMD Durons experienced problems (allegedly it was possible to destroy one if run without heatsink). Now all PC processors will have builtin temperature sensors that feed back into the CPU clock, and will slow down the clock to prevent damage. So you may find that your program is using 100% of available CPU but the CPU is only running at 75% of its rated speed because its cooling is inadequate.

Within a user program is not the correct place to try to manage CPU consumption. Generally your program should alternate between doing things as fast as possible and waiting, suspended, for input or disk access. You should avoid busy-waiting and spinlocking if possible, but as a courtesy to the rest of the system.

Both Windows and Linux have CPU "govenor" systems that will do performance and thermal management. Because this is done at the OS level it can account for total system CPU consumption. It is the responsibility of the operating system to manage the hardware and prevent user programs from misusing it. It is the responsibility of the hardware owner to keep the fans clean and working, and the manufacturer to fit adequate heatsinks and fans in the first place.

There are a few cases where devices have inadequate cooling, but a flood of returns teaches the manufacturers not to do that.

Title: Why should your code not use 100% CPU?


问:
Do objects with validation logic in their domain really represent their real world counterparts?
I asked a question about whether validation behavior should be treated the same as other types of behavior in regard to the concept of OOP being "data + behavior". I got some good answers back that addressed the question from the philosophical point of view and confirmed that the answer to that question seems to be yes.

Now I'd like to address this question from a different angle: Shouldn't objects represent their real world counterparts?

Suppose I give a paper form to someone to fill out. They can pencil in the fields on the form in any order they'd like to and they can even fill in all sorts of incorrect values. When they turn the paper in to me I, representing a broker, may hand it back to them and tell them I can't file it until they fix any invalid entries though.

There's also a comparison to be made between the format of the questions on the paper and a user interface that validates input. Maybe you put checkboxes on the paper and instruct the person to only select one. Of course software can get a lot fancier with this type of validation than a physical sheet of paper, but let's be clear that this type of validation is all in the user interface... validation in the 'domain' simply doesn't exist in the physical realm for this type of object.

Is the paper going to crumple itself up or catch on fire if you write something invalid on it?

So my question is this: if a physical piece of paper has no inherit ability to validate itself, then why would this behavior belong in the domain?

答:
The domain also has a concept of Domain Services. That's still in the domain but could represent the real-world process that you describe.

A mistake that we can make is forgetting that the domain is more than just the Entity objects-- some Services do belong in the domain. One way to get this wrong though is to think that it's wrong to pass a service object into other domain objects including entities.

A straightforward example of doing this correctly is in Jimmy Boogard's talk on Vimeo called "Crafting Wicked Domain Models".  He passes an IOfferCalculator into an Offer Entity object. That's the right thing to do but many developers freak out when then see an object that didn't come from the ORM passed into one that did, even when the reference is temporary.

As far as validation rules go, it really depends on the behavioral consequences of the validation and/or whether or not the same validation rules need to be applied to multiple types.

Personally I see simple validation as an infrastructure service, and try to use a library that does most of the work for things like required fields or minimum string lengths and so on.

For validation that has to do with the state of a single Entity across multiple properties where that state has specific meaning in my model, it absolutely belongs in the entity.


答:
The software doesn't care about representing anything. Everything is ultimately memory being modified and moved around.

Representing a piece of paper in software as an object in the OO sense is because it is useful for us humans to understand both what the software will actually do, against what the software is supposed to be doing, and to be able to make sure those two are in harmony.

So, all these development methodologies and programming language designs orient around making the software understandable and manageable for humans.

Things should only map to the real world to the extent that the model is convenient. For a lot of models, having the model itself do its own validation is most convenient. For others, it's not. But in no sensible development is that decision made on the basis of what a physical piece of paper is capable of.

Title: Do objects with validation logic in their domain really represent their real world counterparts?

Body:
I asked a question about whether validation behavior should be treated the same as other types of behavior in regard to the concept of OOP being "data + behavior". I got some good answers back that addressed the question from the philosophical point of view and confirmed that the answer to that question seems to be yes.

Now I'd like to address this question from a different angle: Shouldn't objects represent their real world counterparts?

Suppose I give a paper form to someone to fill out. They can pencil in the fields on the form in any order they'd like to and they can even fill in all sorts of incorrect values. When they turn the paper in to me I, representing a broker, may hand it back to them and tell them I can't file it until they fix any invalid entries though.

There's also a comparison to be made between the format of the questions on the paper and a user interface that validates input. Maybe you put checkboxes on the paper and instruct the person to only select one. Of course software can get a lot fancier with this type of validation than a physical sheet of paper, but let's be clear that this type of validation is all in the user interface... validation in the 'domain' simply doesn't exist in the physical realm for this type of object.

Is the paper going to crumple itself up or catch on fire if you write something invalid on it?

So my question is this: if a physical piece of paper has no inherit ability to validate itself, then why would this behavior belong in the domain?


答:
Is the paper going to crumple itself up or catch on fire if you write something invalid on it?

No, but some time in the future, paper may be replaced with some form of electronic paper or pads, and they will complain if you make an error.

The point is, there are things that are possible in the virtual world that are not possible in the real world of atoms.  Just because it doesn't exist in the real world doesn't mean you can't or shouldn't model it fictionally in the computer, if that technique suits you, your program, or your customer's requirements.

In the case of input objects, wouldn't it be nice if those objects were capable of telling you "hey, I am invalid" without you having to know anything about them?

Of course, if you are building something like a voting machine or a school test grader that takes in forms with pencil marks or punched holes, naturally the piece of paper isn't going to tell you something bad happened, the machine will.  But before it can, you must first model that paper input in the machine's software, and it is that model that will tell you there is a problem, not the paper.


问:
Backbone/JQuery, ExtJs 4.... is there something else worth looking?
Im currently evaluating a front-end architecture for a big app that will be developed by a team of about 6 developers + 1 web designer so that said, having a robust SVN friendly architecture is a must. So far I'm evaluating this two options:

A mixture of JQuery/UI/Mobile + Backbone/Underscore + Require JS + Twitter-Bootstrap

ExtJS 4

This are the requirements the architecture needs to meet:

SVN Fiendly (or Friendly depending on you previous experiences)

Active community and extensive documentation

Extensible

Easy to learn and to maintain (nice to have)

Cross-browser support (most of the time at least)

Support for Mobile devices

Easy to maintain (MVC, MVVM)

OpenSource (nice to have)

The previously mentioned ones meet most of the requirements in different levels and so far they are the only ones I've found about, am I missing any others?

答: I know this is a bit late, but to keep this post up-to-date, I think AngularJS should be listed as one of the answers.  I prefer a mix of jQuery and AngularJS, and possibly Bootstrap/Angular-UI depending on your UI requirements.</p>


问:
Abstract Class confusion
I have learnt so far that abstract classes can't be instantiated because they are only there for other classes to inherit from. But i cant get my head around this code i came across in the msdn library:

```<code>WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
</code>```

in the documentation it says the above code returns a WebRequest instance.

but the WebRequest class is an abstract class, and how comes the above code returns an instance of an abstract class when abstract classes can't be instantiated.

please relieve me from my agony.

答:
WebRequest is an abstract class that can't be instantiated. WebRequest.Create is a static method that returns a concrete type of System.Net.HttpWebRequest that is a derived subclass of System.Net.WebRequest. Because it is a derived type, it still identifies itself as a WebRequest even though it's fully qualified type name is System.Net.HttpWebRequest.

The reason this is useful is that you no longer need to care about the actual implementation. You know that a WebRequest will have all of the functionality you need so if the concrete type is a System.Net.HttpWebRequest or a Steves.Awesome.WebRequest or a Georges.NotSoAwesome.WebRequest it doesn't matter because they're all inherited from WebRequest.

Your line of code:

```<code>WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
</code>```

This isn't saying that it's actually going to create a WebRequest and only a WebRequest. It's saying that whatever is created will inherit from WebRequest and be compatible with anything you need going forward from the standpoint.

Title: Abstract Class confusion

Body:
WebRequest is an abstract class that can't be instantiated. WebRequest.Create is a static method that returns a concrete type of System.Net.HttpWebRequest that is a derived subclass of System.Net.WebRequest. Because it is a derived type, it still identifies itself as a WebRequest even though it's fully qualified type name is System.Net.HttpWebRequest.

The reason this is useful is that you no longer need to care about the actual implementation. You know that a WebRequest will have all of the functionality you need so if the concrete type is a System.Net.HttpWebRequest or a Steves.Awesome.WebRequest or a Georges.NotSoAwesome.WebRequest it doesn't matter because they're all inherited from WebRequest.

Your line of code:

WebRequest myRequest = WebRequest.Create("http://www.contoso.com");

This isn't saying that it's actually going to create a WebRequest and only a WebRequest. It's saying that whatever is created will inherit from WebRequest and be compatible with anything you need going forward from the standpoint.


答:
There is generally nothing wrong with a program using 100% CPU while it is actually doing useful work and is not taking time away from anything more important.  If a particular hardware platform is e.g. only capable of using 100% CPU continuously for one second before it has to throttle back to 50% to avoid overheating, it is generally better for an application which has useful work to perform to run as fast as it can, and let the CPU or OS handle any necessary throttling, than for an application to guess how fast it "should" run.  If an application or thread has low-priority work to do which would be useful but not at all time critical, it may be helpful for the OS to limit low-priority-task CPU usage to 50% so that if the CPU needs to do something quickly it will be ready to "sprint" for a second, but the application shouldn't worry about such things beyond requesting a low thread priority.

The biggest situations where it's bad to use 100% CPU are when either:

The application is busy-waiting for some event which isn't going to be hastened by persistent polling [and might actually be delayed if the effort wasted checking whether the task is done occupies CPU resources which could otherwise be spent doing the task].

The application is redrawing the display excessively often.  The definition of "excessively often" will depend in some measure upon the nature of the display device and the content being shown.  If display hardware can display 120fps, there may be cases where animation could be shown at 120fps without adding motion blur, but could not be shown cleanly at lower frame rates without adding it.  If rendering a frame with motion blur would take much longer than rendering it without, then rendering at 120fps on hardware which supports it could actually be no more costly than rendering at a slower frame rate with motion blur. [Simple situation: a wheel with 29 spokes, rotating at one revolution per second.  At 120fps, the wheel would appear to rotate with the proper speed and direction; at 60fps, a flickering wheel would appear to rotate slowly in the opposite direction].

The former is clearly recognizable as bad.  The second is a bit more subtle.  If one is targeting a mobile platform, it may be desirable in some cases to allow users to select the desired animation frame rate, since some users may not be worried about battery life but would want the best quality animation, while others would accept lower quality animation in exchange for better battery life.  Rather than having the application try to guess where the trade-off should be, it may be helpful to let the user customize it.

Title: Why should your code not use 100% CPU?


答:
There is some validation that can only be made with reference to the domain, though whether this is an argument that the validation belongs in the domain is moot.

The classification of errors, and hence validation, I am familiar with breaks down into:

Input errors, which can be detected by examination of the input - so a date of 2014-02-30 is self evidently wrong.

Context errors, which can be detected only by examination of the domain object - so a date of birth captured as 1990-01-31, and a date of education starting of 1989-03-02 is incorrect. It is this class of errors that can only be made with reference to the domain.

Lies to the system. These can only be detected by information contained with subsequent events. So if I tell you that my date of birth is 1890-04-25 then (at worst) you may only be able to find that this is incorrect around the year 2010 when I tell you I am still alive and kicking. These errors can only be corrected by remedial actions that will fall outside the system concerned. These remedial actions may be very extensive, or actually impossible to implement.