答:
First I recommend following book scrum-xp-from-the-trenches. Look at page 26 the point about Velocity calculations. The idea is to define a focus factor, and to say that for the next Sprint:

available man-days * focus factor = estimated velocity

estimated velocity is the sum of the estimates of the stories you plan to implement during next Sprint.

And after one Sprint you calculate the lasts Sprint focus factor as:

focus factor = actual velocity / available man-days

where actual velocity is the sum of the estimates of the stories you have implemented during the sprint.

Then you reuse this actual focus factor for the next Sprint, and after a few Sprint you will be able to be more precise with how much you really can achieve during a Sprint...


问:
What is the best design pattern for asynchronous message passing in a Chrome extension?
I have a background script that is responsible for getting and setting data to a localStorage database. My content scripts must communicate with the background script to send and receive data.

Right now I send a JSON object that contains the command and the data to a function. So if I'm trying to add an object to the database I'll create JSON that has a command attribute that is addObject and another object that is the data. Once this is completed the background scripts sends a response back stating that it was successful.

Another use case of the function would be to ask for data in which case it would send an object back rather than a success/fail.

The code gets kind of hacky once I start trying to retrieve the returned object from the background script.

It seems like there is probably a simple design problem to follow here that I'm not familiar with. Some people have suggested future/promise design problems but I haven't found a very good example.

Content Script

```<code>function sendCommand(cmdJson){
chrome.extension.sendRequest(cmdJson, function(response){
    //figure out what to do with response
});
}
</code>```

Background script

```<code>if (request.command == "addObject"){
  db[request.id]= JSON.stringify(request.data);
    sendResponse("success");
}
else if(request.command == "getKeystroke"){
  var keystroke = db[request.id];
  sendResponse(keystroke);
}
</code>```

答:
Well, I am not sure about which pattern you will call it. I would say following looks like Command pattern, I would do this..

```<code>var commands = {
         "addObject":function(request){/*Do something, send response etc*/},
         "getKeystroke":function(request){/*Do something, send response etc*/},
}
</code>```

And in request handler

```<code>var requestHandler = function(request) {
      commands[request.command](request);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Well, I am not sure about which pattern you will call it. I would say following looks like Command pattern, I would do this..

var commands = {
         "addObject":function(request){/*Do something, send response etc*/},
         "getKeystroke":function(request){/*Do something, send response etc*/},
}

And in request handler

var requestHandler = function(request) {
      commands[request.command](request);
}


问:
Continuous Integration : which frequency?
I've always launched builds after each commit, but on this new project, the architects just asked me to change the frequency to "one build every 15 minutes", and I just can't understand why that would be a good reason vs "building on each commit".

First off, some details :

Objective-C (iOS 5) project

10 developpers

each build actually takes ~1 min, and includes build and unit testing.

the integration server is a Mac Mini, so computing power isn't really a problem here

we use Jenkins with the XCode plugin

My arguments were that if you build at each commit, you can see right now what went wrong, and correct directly your errors, without bothering the other devs too often. Plus our tester is less bothered by UT errors this way. His arguments were that devs will be flooded by "build error" mails (which is not completely true, as Jenkins can be configured to send a mail only for the first broken build), and that metrics can't be done properly if the frequency of builds is too high.

So, what's your opinion on this ?

答:
There is literally no point in doing a build every 15 minutes if nothing has changed. But equally there is no downside, afaik, jenkins will only e-mail on fail and then success and not everything in between (eg 10 fails).

We do it on every commit. However we do poll the repository every fifteen minutes and check for changes, maybe that is what yr colleagues are referring to.

You expect your 10 dev's to be committing more than once every fifteen minutes ? That sounds like rather a high estimation.  10 dev's means that after every 150 minutes the same person is committing again, so thats 2.5 hrs. So in your average day each dev commits 3 times.  Personally I do one commit ~ 2 days ... sometimes more sometimes less.


答:
Fail fast is a good principle - the sooner you know the build is broken, the sooner the offending commit can be identified and the build fixed.

Build on every commit is the right thing to do.

Building every 15 minutes can be pointless if the project has a high volume of commits within such a timeframe - tracking down the bad commit would take longer and may be difficult to determine (one might also be in a situation where multiple commits have different things that break the build). There is also the possiblity that in quiet times (night time?) you end up rebuilding though no changes have been made.

If the build breaks so often that it is a problem, the answer it to re-educate the team on the importance of not breaking the build and in techniques that ensure this does not happen (frequent fetches, checkin dance, compiling and running unit tests locally etc...).

Title: Continuous Integration : which frequency?

Body:
I've always launched builds after each commit, but on this new project, the architects just asked me to change the frequency to "one build every 15 minutes", and I just can't understand why that would be a good reason vs "building on each commit".

First off, some details :

Objective-C (iOS 5) project

10 developpers

each build actually takes ~1 min, and includes build and unit testing.

the integration server is a Mac Mini, so computing power isn't really a problem here

we use Jenkins with the XCode plugin

My arguments were that if you build at each commit, you can see right now what went wrong, and correct directly your errors, without bothering the other devs too often. Plus our tester is less bothered by UT errors this way. His arguments were that devs will be flooded by "build error" mails (which is not completely true, as Jenkins can be configured to send a mail only for the first broken build), and that metrics can't be done properly if the frequency of builds is too high.

So, what's your opinion on this ?


答:
Perhaps the requirement shold be "build at most once per 15 minutes". This could make sense for projects with very frequent commit activity (i.e. multiple commits within few minutes) and perhaps long build times. Of course it depends also on how the builds are used. For testers it might be somewhat confusing to get multiple builds within 15 minutes ...

But I agree that it makes no sens to build if nothing has changed.


问:
How serious is losing the source code?
If a software company loses the source code to one of the products they are selling, how serious would that be, in terms you could explain to a layman?  Would the term "gross negligence" be too strong?  Or "gross incompetence"?  Obviously no one got killed but isn't it as serious as some financial negligence that people get jail time for?

EDIT:
Let's say it's not a case of a disk drive crashing, natural disaster or anything like that.  Just they misplaced it.

答:
I would liken it to other jobs that require construction of an item. Likely something physical. e.g. If an architect lost the plans for a building that was built; If an automobile company lost the plans for a model of car; If a seamstress lost the pattern for an outfit they had made; etc.

There are many jobs that have physical comparisons to liken to creating software.

ContentLicense: CC BY-SA 2.5

Title: How serious is losing the source code?


答:
It's going to flood developers with mail more if it's every 15 minutes only. That's because it won't know for certain who broke the build and thus mail more people.

As for metrics, if it's really a problem—which I can't tell because I don't know what metrics they think there is a problem with—, you can always make another job for collecting the metrics.


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答: This is a terrible idea.  You want your developers to be as productive as possible, which means giving them as fast a machine as possible, so they don't sit around all day waiting for things to compile.  (Slightly OT, but it also helps not to block their access to potentially helpful sites with WebSense and the like.)  If you are constrained by having users who are still running Stone-Age technology, then you'll need to have a test machine with similar specs, and be sure to test early and often to make sure that you aren't going down the wrong road in terms of technology choices.</p>


问:
What should I be responsible for as the first developer in a large scale web project?
I am the first developer in a large scale web project, in the real estate sector.
I am not an expert in any field, I know the basic of all, programming, databases, something about design and a little bit about SEO, and website optimization / caching. And I have some knowledge about other technologies and stuff that could be required in the project.

So I am a developer, my boss does some drawing on a paper to present me his ideas and then I start programming and I show him the result. Until now there was no problem, but now the web application is large enough, and it lacks a little bit of database optimization and intuitive user interface. Beside the website, the project also has an offline newspaper, and a desktop application that is a reduced version of the online one, both this things are not managed by me, but by other people or developers that are external to the company.

We do not use a collaboration tool for sharing knowledge between the people working on this project, just emails, and we do not use a development methodology, as for the team, we are:

the developer(me),

a designer,

a secretary, and

the boss.

I have the possibility to ask the boss hire the people I want so I can increase the team and have the right person dealing with the right part of the project.

This is the story, the real question is, what should be my attitude towards the project and the company? Should I stay a developer and participate in taking decisions and organizing tasks from time to time to help the boss? Or should I get more serious about this and try to learn project management and implement everything I consider it's required to ensure the quality of the work and final results?

I am the one who best knows what has been developed until now, should I try to organize all the work and the team? Or should I ask my boss to hire some expert to do that?

答:
Your job primarily requires interation with 5 entities :

Your boss. Make sure he is informed and appraised of progress (and lack of progress!).

The designer. You need to make sure the design is technically feasable, and implemented correctly.

The code. You need to make sure that all of the code follows the design paradigms setup by the designer.

Any development underlings, you need to review their work, and make sure that it conforms to the design, not just in their little sphere of influence, but across the whole system.

The secretary. Always be nice to the secretary.

In this you essentially take the dual roles of technical advisor and software development manager :)


问:
Is CSS resizing of images still a bad idea?
It's always been looked at that using width/height attributes on images which aren't what the original image actual is is a bad idea. It could mean pixalated images or download sizes bigger than nessary.

But, is this still an issue? I wouldn't suggest up-sizing photos, but downsizing shouldn't be an issue provided that its not too much of a difference from the original and keeping to scale.

For example, I have a photo that is 600x400 and I stick a width of 400px on it. Most modern browser scale the image down and it looks like rendering is still decent.

So, what is everyones view on this?

答:
Don't worry about the scaling (most browsers will make scaled images look just fine, in my experience), worry about the size of the payload you've sent to the end-user.

Sure, you could argue that you're only wasting a tiny amount of bandwidth on both ends for those extra pixels you're sending with no intention of using, but there's a time cost too.

For every image you send at a size that's above what's needed you add a tiny bit of delay to the page load for your user. For websites wtih only a couple of images this won't be an issue, but for a site with a large number of supporting assets you'll start to add noticeable delay, and delay will cost you money.

Also, with regards to the tiny bandwidth cost, as your site's traffic goes up, so will the tiny bandwidth cost.

So, save your company money and spend the 30 seconds you'll need to re-size the image yourself! :)


问:
Object orientated data structures in database driven applications
I've started working for a company that maintains a small/medium sized commercial website. The website is written in c# asp.net, and uses SQL Server as a database. The structure of the code is very messy at the moment (for instance, ~5000 line Utility.cs file) so I want to move towards a better design on the asp.net side of the application.

I'm trying to figure out the right way to do this. My basic plan is to create a class for every logically distinct item in the application (mostly mapping 1-1 to database tables, but sometimes N-1 or 1-N). Then, I plan to have some static factory methods to instantiate these classes by querying the database. The developer should be able to manipulate the resultant object, and then use a UpdateDatabase() method to save the changes to the database.

For example, here is how an Email object would work:

```<code>public class Email {
    Guid userId;
    Guid emailId;
    String emailValueInitial = null;
    Sting emailValueNew = null;

    private Email();

    public static Email RetrieveEmail(Guid UserId, Guid EmailId) {
        // .. query
        return new Email(UserId,EmailId,emailValueInitial);
    }

    public String EmailValue {
        get {
            if (emailValueNew == null) return emailValueInitial;
            else return emailValueNew;
        }
        set {
            emailValueNew = value;
        }
    }

    public bool Update() {
       // .. update database with value of emailValueNew or do nothing if it hasn't
       // been changed
    }

}
</code>```

Notes:

I could update the database whenever a field is changed, but this is obviously inefficient.

I don't know what to do in the event that the developer wants to insert a null value into the database - I suppose I need different concepts for 'null as variable not yet used' vs 'null as database value null'.

The above is a simple case. I'd also need some way of knowing about many-one relationships in tables. For instance, a User could work like this:

```<code>public class User {
    Guid userId;

    public Emails emails = new Emails(userId);

    private User(); // etc..

    public RetrieveUser();
    public CreateUser();

    public Update();
}

public class Emails {
    List<Email> emails = new List<Email>();

    Guid userId;

    public Emails(Guid userId); // etc..

    public bool CreateEmail(); // its convinient to create/delete from here
    public bool DeleteEmail(); // as I can enforce, say, minimum 1 email per user
}
</code>```

These above are my first thoughts on how to solve this problem, but I've never done anything like this before, and I don't know what problems I might come across. I want to make a system that will be scaleable and easy to develop as we take on more programmers, so its really important to get the initial design correct.

What kind of design should I use in an object-orientated language to best represent and link with a database? What are important things to consider? Is there existing literature on this subject, or important libraries/constructs I have neglected?

答:
I would suggest taking a serious look at ORM solutions like entity framework and nhibernate.

Then I would suggest drawning up a vision of where you want the architecture to move to over time. stick that on the wall, and tell every developer about. Take their feedback and improve it. And make sure that every developer buys into the vision.

Then to move towards the vision I'd take an iterative and test-driven approach of bringing different parts of the system under test and improving it towards the vision incrementally. For much more on how to approach this part please read Michael Feahters' Working Effectively with Legacy Code.


问:
Re-inventing system design for Scala
Many, many, moons ago, I did my masters in Object Orientated Software Engineering. I covered everything: project initiation, requirements, analysis, design, architecture, development, etc, etc. My favourite IT book of all time was Developing Object Oriented Software, an Experience Based Approach (IBM-1996). A book created by a group of true experts of their time. It describes a work product centric approach to object oriented analysis, design and development methods.

I designed and developed and was happy and at the top of my game, but I started to feel a little dated: Agile movements became fashion of the day and re-branded some well known iterative and incremental approaches with new hip words. Suddenly inexperienced developers started frowning when I said "requirements" or "architecture" as if these things were superseded by magic.

Design and development lost it's fun and I was about to leave the whole IT industry behind me.

Then I discovered Scala. Oh, like soft rain on a dusty road. Everything just became clear, the air became sweet again and the little light of my hard-drive would flicker deep into the night, merrily keeping me company in my world of discovery.

I like system design. I'm an architect at heart, more than a programmer. I love analyzing, designing, thinking, arguing, improving - I just love simple, clean and crisp designs.

How do we design pure Scala solutions?

Surely conventional sequence diagrams, interaction diagrams, object diagrams, etc, could all be replaced or improved for the goodness of blending imperative and functional object orientated systems. Surely there is an opening for something totally different!

I'm not looking for bloated complexity - I'm looking for flexible simplicity. Much like Scala is actually simple and easy (albeit different), but can be extended to fit your requirement like a pair of Yoga pants. There must be a design system for this lovely language that will start simple, and can be extended to fit your requirements and your domain. Surely UML can not be it!

So how do we design pure Scala systems? Imagine for a moment, you have the luxury to design a complete system from scratch, and know that you will only be using Scala - How will your models look? What types of diagrams would you have to describe structure and behaviour? How would you model Options, matches, mixins, singleton Objects, etc. without being drawn into the complexity of extending existing modeling techniques rather than a fresh, light-weight, innovative tool-set.

Does such a design/process/solution exist, or is it time to invent one?

答:
I can't really give an answer to this question, but let me offer some thoughts.

I am a computer engineering student in a university, and last semester me and a group did a large software project in which our primary language was Scala. We did our design the traditional way: use cases, a domain model, sequence diagrams, UML class diagrams; the usual load. And, as you are already aware, they are a poor fit. Here are some reasons.

First, consider sequence diagrams. The feel of a sequence diagram is of a few stable, long-lived, semi-autonomous actors talking to each other. In Scala, objects tend to be created for a short time. Furthermore case classes encourage "dumb" objects, with only data and no code, so the concept of passing messages is out of place. But the hardest challenge for sequence diagrams is that they have no good way of incorporating first-class functions; in an OO design using only a callback here or there it can be made to work, but if that is your primary means of transferring control you will find the sequence diagram reflects little of your actual code.

UML class diagrams are more amenable to Scala; yes, mixins don't come through well, but that is something that could be "tweaked" rather than overhauled. But I think that might be missing the point.

Consider again why Scala has "dumb objects". If you write a case class with no methods:

```<code>case class NewInvite(user: User, league: League)
</code>```

you don't need any methods, because the types of the members promise something about what you can do with them. In fact, they promise everything. And, in every scope within the program, the variables within scope and their types promise something about where the code can go at that point.

So, maybe, if we step back a bit, and, instead of thinking minutely about types per se, design our program in terms of what contexts our code will live in, and what is promised to the programmer (and, eventually, the user) in each of these contexts, we will find a description more appropriate to Scala. However I am only guessing here, and I think you are right that much more needs to be explored in this area.

OwnerDisplayName: JacobusR

Title: Re-inventing system design for Scala

Body:
I can't really give an answer to this question, but let me offer some thoughts.

I am a computer engineering student in a university, and last semester me and a group did a large software project in which our primary language was Scala. We did our design the traditional way: use cases, a domain model, sequence diagrams, UML class diagrams; the usual load. And, as you are already aware, they are a poor fit. Here are some reasons.

First, consider sequence diagrams. The feel of a sequence diagram is of a few stable, long-lived, semi-autonomous actors talking to each other. In Scala, objects tend to be created for a short time. Furthermore case classes encourage "dumb" objects, with only data and no code, so the concept of passing messages is out of place. But the hardest challenge for sequence diagrams is that they have no good way of incorporating first-class functions; in an OO design using only a callback here or there it can be made to work, but if that is your primary means of transferring control you will find the sequence diagram reflects little of your actual code.

UML class diagrams are more amenable to Scala; yes, mixins don't come through well, but that is something that could be "tweaked" rather than overhauled. But I think that might be missing the point.

Consider again why Scala has "dumb objects". If you write a case class with no methods:

case class NewInvite(user: User, league: League)

you don't need any methods, because the types of the members promise something about what you can do with them. In fact, they promise everything. And, in every scope within the program, the variables within scope and their types promise something about where the code can go at that point.

So, maybe, if we step back a bit, and, instead of thinking minutely about types per se, design our program in terms of what contexts our code will live in, and what is promised to the programmer (and, eventually, the user) in each of these contexts, we will find a description more appropriate to Scala. However I am only guessing here, and I think you are right that much more needs to be explored in this area.

OwnerDisplayName: Owen


问:
Our version of Agile isn't working. Tips?
I work on a small team of 4 developers. We are implementing a version of Agile that seems to continuously provide us with the same difficulties, week after week, and I'm looking for suggestions that can help us improve our process.

The background:

We generally do 2 week sprints, and each sprint we tend to underestimate our work, and we get in trouble with our manager because we're behind schedule.

We start off each sprint by tasking out the stories that our manager creates for us. Sometimes he throws in the tasks too and we estimate them. We don't use story points. We use the software Urban Turtle to "manage our sprints", which is essentially just stories and tasks, and the associated burn down. We don't plan for a release at the end of a sprint.

The most common issue that occurs is that we plan for a task in the beginning of a sprint only to discover it's much larger in scope, but still high in the priority, so we need to work additional hours on it. The second most common issue is that one of us runs into a technical problem that slows down the hours burned, causing a roadblock.

The only suggestion provided to us is to be more proactive in adjusting our estimates and providing updates during standups in the morning so we can adjust for the extra time needed.

However, there seems to be something fundamentally wrong with the way we're doing things. Perhaps there's a disconnect between the expectations of the manager on a project level and the expectations on a sprint level. Because we're making these sprint iterations according to a project plan, and therefore extending a sprint or deferring items screws up the project plan. So as developers we are being encouraged to perform Agile by extending estimates when necessary but also complete the sprint on time, which is confusing.

This can't be an uncommon problem, so I'm hoping those wiser than I out there have a suggestion or two on how we can stop running into this same problem every sprint. It's frustrating.

答:
Are you trying to allocate 100% of your time? If so, stop doing that. Begin by adding up all the hours your team has to contribute during the sprint. Do this by assuming each worker will at best put 6 hours a day toward the project. This is considered an "ideal day". Those other two hours? Sucked up by meetings, breaks, administrative tasks, that time in the morning when you're reading email and planning your day, etc. This isn't "hedging your bets" or "sandbagging", it's being realistic.

Second, multiply that 6 hours/day by 80%. Why? Because as humans we suck at predicting how much time a task will take. This accounts for errors in our judgement. Again, not sandbagging, it's being realistic.

Now you have a number representing a realistic number of hours you expect to apply directly toward your tasks. When you are estimating, stop adding stories when the next story would put you over.

Finally, don't let the product owner add tasks. Scrum planning is for the team, the PO is not part of the team doing the work. Of course, in the real world if the PO is more knowledgeable than anyone on the team her input can be very useful. Still, if the team is taking the heat for being behind, the team needs to take ownership of exactly what tasks they will do. Your goal is to be able to meet the acceptance criteria; if a task doesn't lead directly to that, don't do it.

Remember, Scrum isn't about being more productive. It's about being more open and communicative. The work will take whatever it takes to get done. Scrum is there to make it easier to estimate, easier to communicate with stakeholders, and easier for your team to make a commitment.

OwnerDisplayName: letsgetsilly


答:
Some devs want to be allowed to do commits in a way where the files belonging to one functional change are not committed in one single, atomic procedure. They need two or three minutes to do a "logical commit", which consists of some "physical commits". This is typically the case when your devs directly commit to a central repository, not using a DVCS.

For this cases, it may be a good idea to let your CI server wait some time after the last commit before starting a new build. But 15 minutes seem to be a very high number, 5 minutes or less should be enough.

Or, better(!), try to guide your devs to work only in small portions, only one thing at a time, making it much easier to do only "functional complete" physical commits. Then a build after every commit will work seemlessly.


问:
Should I open up to .net, c# and visual basic?
I am a huge linux fan and have been ignoring .net, C#, and visual basic due to their relationship with Microsoft. Am I foredooming them just for their relationship?

Is there any advantage to learning them, when you are mainly a linux user?

答:
If you prefer Linux to Microsoft, then getting into .Net isn't really a good idea. .Net is fundamentally tied to Microsoft.

C# is a nice enough language and it's true that you can use Mono on Linux. However it's not exactly a comfortable place to be - Mono isn't 100% compatible with Microsoft .Net and probably never will be. This is because of patent threats, various Windows-specific features and the fact that even if C# itself is standardised by ECMA, most of the rest of the .Net platform isn't. Furthermore the Mono ecosystem on it's own is small compared to other open source languages.

I think you'd be much better of looking at the new JVM languages (Scala, Clojure, JRuby, Groovy are probably the most promising). Reasons:

They all benefit from running on the JVM, which is an awesome platform (whatever you think about Java itself...)

They are all open source, properly cross-platform and a great fit for Linux

The languages themselves are great and IMHO better than the .Net equivalents (Scala > C#  for OOP, Clojure > F# for FP, JRuby+Rails > ASP.NET)

They can benefit from using all the tool and libraries in the massive Java ecosystem, which is again mostly based on open source.


问:
Unit testing invalid inputs; ArgumentException vs. Custom Exception
In unit tested code I often have multiple checks on the arguments on any method before the actual "work" of the method is begun:

```<code>public void DoSomething(string test)
{
   if (string.IsNullEmptyOrWhiteSpace(test))
   {
       throw new ArgumentException("Test must not be empty", "test");
   }
}
</code>```

In my corresponding test for this method I'll do the following:

```<code>[Test]
[ExpectedException(typeof(ArgumentException),
    Message = "Parameter name: test",
    MatchType = MatchType.Contains)]
public void TestNullInput()
{
    var classToTest = new ClassToTest();
    classToTest.DoSomething(null);
}
</code>```

I'm thinking that this is quite a bad way to go about doing the test, however, as it relies on a specific named parameter (which does not necessarily hold true after any refactoring), as well as the format of the message of an ArgumentException.

Another option might be to create a custom exception for this, some form of "TestWasNullOrEmptyException", but this also seems fairly awkward, as there will be many many different exceptions throughout the solution, each used to indicate only the absence/invalidity of a parameter.

I am wondering if anyone else has dealt with this issue, and whether I'm simply going about my input validation tests the wrong way of it there's a more elegant solution.

EDIT: This is C# code, and I'm using NUnit/Rhino Mocks.

答:
What test framework are you using? Looks similar to junit (ExpectedException, MatchType), but the square bracket syntax is new to me. Is this c#'s NUNIT?

I use junit 4's ExpectedException in a programatic way. Therefore, I can set a lot of attributes of the Exception, like thrown.expectMessage(startsWith("What"));. For me, this is sufficiently flexible.

Another option might be to create a custom exception for this, some
  form of "TestWasNullOrEmptyException"

That does not seem to be good idea. With that argument, you could never use a general exception. But abstraction is good, to cope with complexity. In your case, thousands of new Exception classes, that also have to be caught and handled somewhere, would produce the complexity that can better be dealt with via more abstract exceptions, like ArgumentException.


问:
Is there a canonical book on design patterns?
I am interested in learning design patterns and would like to know what are considered top tier books in learning this subject.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on design patterns? What about that book makes it special?

答:
"Agile Principles, Patterns, and Practices in C#" by Robert C. Martin.  I think he has a Java version of the book as well.

Also, not a pattern itself, but Domain Driven Design has some great concepts even if you don't go for the full DDD approach.

```<code>  * Ubiquitous Language
  * Code first approach (vs. DB first)
  * etc.
</code>```

Body:
"Agile Principles, Patterns, and Practices in C#" by Robert C. Martin.  I think he has a Java version of the book as well.

Also, not a pattern itself, but Domain Driven Design has some great concepts even if you don't go for the full DDD approach.

  * Ubiquitous Language
  * Code first approach (vs. DB first)
  * etc.

OwnerDisplayName: Kevin Nelson


问:
Examples of operator overloading, which make sense
While I learning C#, I found that, the C# supports operator overloading. I have problem with good example which:

Make sense (ex. adding class named sheep and cow)

Is not an example of concatenation of two strings

Examples from Base Class Library are welcome.

答:
The first example that comes to my mind is the implementation of BigInteger, which allows you to work with large signed integers.
Check out the MSDN link to see how many operators have been overloaded (that is, there is a big list, and I did not check if all operators have been overloaded, but it certainly seems so)

Also, since I also do Java and Java does not allow overloading operators, it's incredibly sweeter to write

```<code>BigInteger bi = new BigInteger(0);
bi += 10;
</code>```

Than, in Java:

```<code>BigDecimal bd = new BigDecimal(0);
bd = bd.add(new BigDecimal(10));
</code>```

Body:
The first example that comes to my mind is the implementation of BigInteger, which allows you to work with large signed integers.
Check out the MSDN link to see how many operators have been overloaded (that is, there is a big list, and I did not check if all operators have been overloaded, but it certainly seems so)

Also, since I also do Java and Java does not allow overloading operators, it's incredibly sweeter to write

BigInteger bi = new BigInteger(0);
bi += 10;

Than, in Java:

BigDecimal bd = new BigDecimal(0);
bd = bd.add(new BigDecimal(10));


答:
The key example is operator==/operator!=.

If you want to easily compare two objects with by data values instead of by reference, you'll want to overload .Equals (and.GetHashCode!), and might want to do the != and == operators as well for consistency.

I've never seen any wild overloads of other operators in C# though (I imagine there are edge cases where it might be useful though).

Title: Examples of operator overloading, which make sense

Body:
While I learning C#, I found that, the C# supports operator overloading. I have problem with good example which:

Make sense (ex. adding class named sheep and cow)

Is not an example of concatenation of two strings

Examples from Base Class Library are welcome.


答:
This example from MSDN shows how to implement complex numbers and have them use the normal + operator.

Another example shows how to do it for matrix addition, and also explains how not to use it to add a car to a garage (read the link).


答:
As always, do your benchmarking, but unless the app is really popular/mission-critical, I wouldn't be too worried about downsizing from 600 to 400 if you're in a situation where you need to change the width frequently. If it's a one-off, sure, run convert -geometry 400x photo1.jpg photo2.jpg, but if it's an app you're iterating fast on, there are probably more important things to worry about, even within the realm of performance. e.g. latency; pre-emptively loading images, for example.

Image size can be important on mobile devices, where large image sizes have the triple-whammy effect of loading slowly (mobile broadband), taking longer to render (lower-grade hardware), and - once rendered - not being fully visible at high resolution anyway.

You might also want to look into responsive images. There's a lot of work people have done, for example automatically downsizing - and then caching - images on the server is a good approach if this comes up a lot.

Title: Is CSS resizing of images still a bad idea?

Body:
It's always been looked at that using width/height attributes on images which aren't what the original image actual is is a bad idea. It could mean pixalated images or download sizes bigger than nessary.

But, is this still an issue? I wouldn't suggest up-sizing photos, but downsizing shouldn't be an issue provided that its not too much of a difference from the original and keeping to scale.

For example, I have a photo that is 600x400 and I stick a width of 400px on it. Most modern browser scale the image down and it looks like rendering is still decent.

So, what is everyones view on this?


答:
The obvious examples of appropriate operator overloading are any classes which behave in the same way that numbers operate. So BigInt classes (as Jalayn suggests), complex numbers or matrix classes (as Superbest suggests) all have the same operations that ordinary numbers have so map really well onto mathematical operators, while time operations (as suggested by svick) map nicely onto a subset of those operations.

Slightly more abstractly, operators could be used when performing set like operations, so operator+ could be a union, operator- could be a complement etc. This does start to stretch the paradigm though, especially if you use the addition or multiply operator for an operation which isn't commutative, as you might expect them to be.

C# itself has an excellent example of non-numeric operator overloading. It uses += and -= to add and subtract delegates, i.e. register and de-register them. This works well because the += and -= operators work as you would expect them to, and this result in much more concise code.

For the purist, one of the problems with the string + operator is that it isn't commutative. "a"+"b" is not the same as "b"+"a". We understand this exception for strings because it is so common, but how can we tell if using operator+ on other types will be commutative or not? Most people will assume that it is, unless the object is string-like, but you never really know what people will assume.

As with strings, the foibles of matrices are pretty well known too. It is obvious that Matrix operator* (double, Matrix) is a scalar multiplication, whereas Matrix operator* (Matrix, Matrix) would be a matrix multiplication (i.e. a matrix of dot-product multiplications) for instance.

Similarly the use of operators with delegates is so obviously far removed from maths that you are unlikely to make those mistakes.

Incidentally, at the 2011 ACCU conference, Roger Orr & Steve Love presented a session on Some objects are more equal than others - a look at the many meanings of equality, value and identity. Their slides are downloadable, as is Richard Harris' Appendix about floating point equality. Summary: Be very careful with operator==, here be dragons!

Operator overloading is a very powerful semantic technique, but it is easy to over-use. Ideally you should only use it in situations when it is very clear from context what the effect of an overloaded operator is. In many ways a.union(b) is clearer than a+b, and a*b is much more obscure than a.cartesianProduct(b), especially since the result of a cartesian product would be a SetLike<Tuple<T,T>> rather than a SetLike<T>.

The real problems with operator overloading come when a programmer assumes a class will behave in one way, but it actually behaves in another. This sort of semantic clash is what I'm suggesting it is important to try to avoid.


答:
You're right that OOD is limited and outdated. Its main advantage is that it is so well specified and ritualised, with fancy names for each and every trivial pattern and design trick. You won't find any comparable system for the more modern and rational approaches to the systems design.

I can only list a couple of things: a semantic approach to design, a subset of which is called Language-Oriented Programming (and is heavily used by the Scala community) and Domain-Driven Design. The latter is an oversimplified and OOPised view on a more generic semantic design approach, you'll only be able enjoy it if you like OOD.

I'd also recommend to learn a trick or two from the other functional programming communities - e.g. Haskell and Scheme, not all of their design know-how had already been transfered to Scala.

Title: Re-inventing system design for Scala

Body:
Many, many, moons ago, I did my masters in Object Orientated Software Engineering. I covered everything: project initiation, requirements, analysis, design, architecture, development, etc, etc. My favourite IT book of all time was Developing Object Oriented Software, an Experience Based Approach (IBM-1996). A book created by a group of true experts of their time. It describes a work product centric approach to object oriented analysis, design and development methods.

I designed and developed and was happy and at the top of my game, but I started to feel a little dated: Agile movements became fashion of the day and re-branded some well known iterative and incremental approaches with new hip words. Suddenly inexperienced developers started frowning when I said "requirements" or "architecture" as if these things were superseded by magic.

Design and development lost it's fun and I was about to leave the whole IT industry behind me.

Then I discovered Scala. Oh, like soft rain on a dusty road. Everything just became clear, the air became sweet again and the little light of my hard-drive would flicker deep into the night, merrily keeping me company in my world of discovery.

I like system design. I'm an architect at heart, more than a programmer. I love analyzing, designing, thinking, arguing, improving - I just love simple, clean and crisp designs.

How do we design pure Scala solutions?

Surely conventional sequence diagrams, interaction diagrams, object diagrams, etc, could all be replaced or improved for the goodness of blending imperative and functional object orientated systems. Surely there is an opening for something totally different!

I'm not looking for bloated complexity - I'm looking for flexible simplicity. Much like Scala is actually simple and easy (albeit different), but can be extended to fit your requirement like a pair of Yoga pants. There must be a design system for this lovely language that will start simple, and can be extended to fit your requirements and your domain. Surely UML can not be it!

So how do we design pure Scala systems? Imagine for a moment, you have the luxury to design a complete system from scratch, and know that you will only be using Scala - How will your models look? What types of diagrams would you have to describe structure and behaviour? How would you model Options, matches, mixins, singleton Objects, etc. without being drawn into the complexity of extending existing modeling techniques rather than a fresh, light-weight, innovative tool-set.

Does such a design/process/solution exist, or is it time to invent one?


问:
What are ways of drafting a workflow document that maps elements in the design close to their counterparts in code?
We're starting a medium sized PHP web app, written in MVC fashion, using CodeIgniter. Most of the functional specifications have been written, and there are a few features that will definitely be replaced with improved behaviour in later stages of the project.

I'm tasked with writing a workflow document from a technical point of view and here's what I want to cover, ideally:

The document should preferably be a diagram of some sort,

A close mapping of elements in the document with with models/views/controllers/js functions/other important blocks in the code; let's call these modules

That will suffice since I will be able to derive from that a way to test different modules independently and assign different modules to different programmers.

The aspect of rewriting parts of the document when I discover that parts of the code need to be replaced isn't an issue, I'll make the rewrites to keep code and diagram in sync if/when I have to.

My attempts so far with Petri nets and UML interaction diagrams have failed upon the realization that I have to expose too much of the decision making logic inside controllers.

I'm looking for advice and I'm curious if anyone has done this before.

答:
I'm going to attempt an answer, although I'm not sure what you mean by "elements" in your question.

Bad ASCII art follows:

```<code>--------------                                      -----------------
|  element   | -------- is created by ------------  |    module     |
--------------                                      -----------------

--------------                                      -----------------
|  element   | -------- is modified by -----------  |    module     |
--------------                                      -----------------
</code>```

Basically, element is acted upon by module(s).  You could tie more than one module to an element.

Body:
I'm going to attempt an answer, although I'm not sure what you mean by "elements" in your question.

Bad ASCII art follows:

--------------                                      -----------------
|  element   | -------- is created by ------------  |    module     |
--------------                                      -----------------

--------------                                      -----------------
|  element   | -------- is modified by -----------  |    module     |
--------------                                      -----------------

Basically, element is acted upon by module(s).  You could tie more than one module to an element.


问:
F# performance vs Erlang performance, is there proof the Erlang's VM is faster?
I've been putting time into learning functional programming and I've come to the part where I want to start writing a project instead of just dabbling in tutorials/examples.

While doing my research, I've found that Erlang seems to be a pretty powerful when it comes to writing concurrent software (which is my goal), but resources and tools for development aren't as mature as Microsoft development products.

F# can run on linux (Mono) so that requirement is met, but while looking around on the internet I cannot find any comparisons of F# vs Erlang.  Right now, I am leaning towards Erlang just because it seems to have the most press, but I am curious if there is really any performance difference between the two systems.

Since I am used to developing in .NET, I can probably get up to speed with F# a lot faster than Erlang, but I cannot find any resource to convince me that F# is just as scalable as Erlang.

I am most interested in simulation, which is going to be firing a lot of quickly processed messages to persistent nodes.

If I have not done a good job with what I am trying to ask, please ask for more verification.

答:
Few objective statements can be made on this subject because the performance of these two languages is strongly dependent upon the application and programming style.

The only advice I can give is that F# has the performance advantage of a static type system and the CLR does a good job leveraging this in order to improve performance. F# does have asynchronous agents and message passing but it has not been optimized and synchronous code is often over 10× faster.

Erlang is dynamically typed which puts its at a significant disadvantage in terms of performance (expect a lot more boxing) but it was built from the ground up to support fast message passing between asynchronous agents so that may well be a lot faster than the equivalent F#. However, I have no benchmark results to back this up: it is just my expectation.

As an aside, both Erlang and F# are relatively fringe languages with small communities and, due to their different target markets, people familiar with both are rare. The only person I can think of who nearly qualifies is Jesper Louis Andersen but I'm not sure how much F# he has done.


问:
Can you point me to a nontrivial strategy pattern implementation?
We are faced implementing a registration workflow with many branches. There are three main flows which in some conditions lead to one another. Each flow has at least four different steps; some steps interact with the server, and every step adds more information to the state. Also the requirement is to have it persistent between sessions, so if the user closes the app (this is a mobile app), it will restore the process from the last completed step with the state from the previous session.

I think this could benefit from the use of the strategy pattern, but I've never had to implement it for such a complex case. Does anyone know of any examples in open source or articles from which I could find inspiration? Preferably the examples would be from a live/working/stable application.

I'm interested in Java implementation mostly; we are developing for Java mobile phones: android, blackberry and J2ME. We have an SDK which is quite well separated from platform specific implementations, but examples in C++, C#, Objective-C or Python would be acceptable.

答:
As Kevin Junhans already pointed out, this problem is really a question about implementing a workflow.

The strategy pattern isn't really applicable, it's purpose is more to make code generic by swapping out small portions of logic contained in "Strategies", not in orchestrating a larger process.

For Java there are a lot of workflow related options, of which I know two free and open source ones:

jBpm

Activiti

A good workflow engine will help persist long running processes (like when a user exits their session) and orchestrate actions between multiple systems (wait for user input here, call web service here, etc). Done right, your processes will also be easier to adjust in the future and verify with the business.


问:
Use Case Structure
I am creating use cases for a project.  A generic user is extended by user "categories" which then is extended by an administrator (that can do all tasks possible).

Is the following acceptable to portray? Is there a better way to portray such info?

答: To me, it looks like you're drawing a Class Diagram, but with fancy stick figures instead of boxes. IMO Use Case Diagrams should show how a person or other entity acts or reacts under certain conditions. I fail to see how extending a client is something an administrator does as part of his job, or something an administrator object could be capable of.

ContentLicense: CC BY-SA 4.0

Title: Use Case Structure


答:
Good use of overload can be rare, but it does happen.

overloading operator== and operator!= show two schools of thought: those for saying it makes things easier, and those against saying it prevents comparing addresses (i.e. am I pointing to the exact same place in memory, not just a copy of the same object).

I find cast operator overloads to be handy in specific situations. For example, I had to serialize/deserialize in XML a boolean represented as 0 or 1. The right (implicit or explicit, I forget) cast operator from boolean to int and back did the trick.


问:
Determining if language/framework/technology is 'Future-proof'
I'm a PHP developer and I recently started to work with CodeIgniter. It seems that whenever I search for something related to CodeIgniter, the blog posts and what not are usually from '09 or '10, so it got me thinking, is CodeIgniter still relevant and is it going to be in the future? Is there another framework that is taking it's place?

The same goes for other languages and frameworks as well. At what point do you abandon learning certain languages or frameworks? Is there any easy way to find those that are emerging and worth picking up?

答:
I can answer whether a particular technology is future proof - the answer is almost certainly no, since you didn't put a timescale on this.

To make this question answerable you're going to need to add some more detail to the requirements. For example:

What timescale are we talking about - 1 year, 3 years, 5+ years ?

What would be the cost of picking something that is not around in 5 years time ?

What benefits will you get from choosing a less "safe" option, and do the benefits outweigh the risks ?

The choice of a language/framework/technology is really a part of risk management in the project.  As with all risks you'll need to consider a number of factors (I'm trying to keep this short) and then take steps to reduce it to a level appropriate to the situation in hand.

Like with most things in life, the activity that involves the lowest risk may not actually be the best choice.

In short, how much uncertainty are you prepared to live with compared to the benefits you are going to reap from using  over the expected life time of the project.

The longer you want to look in to the future, the less certainty there is going to be. If you are happy with only worrying about the next 2 years for example, your choice will be far easier to make (and leave far more options open to you) than picking something that needs to be around for the next 10 years.


问:
Should you use C# and F# together
I know you can use C# and F# together in the same project however I'm not sure if its a good idea to do so.

It seems to me that mixing two very different coding styles (functional vs OOP) could cause a lack of cohesion in the design. Is this correct?

答:
It seems to me that mixing two very different coding styles (functional vs OO) could cause a lack of cohesion in the design. Is that correct?

I don't think you'll get a "lack of cohesion". Each language has strengths and weaknesses. Combining them on a common-language run-time lets you get closer to the best of both worlds. With C# and F#, you just want to make sure you use the intersection of the two languages at the interface between the two in your solution.

Title: Should you use C# and F# together


问:
Continuous Integration : which frequency?
I've always launched builds after each commit, but on this new project, the architects just asked me to change the frequency to "one build every 15 minutes", and I just can't understand why that would be a good reason vs "building on each commit".

First off, some details :

Objective-C (iOS 5) project

10 developpers

each build actually takes ~1 min, and includes build and unit testing.

the integration server is a Mac Mini, so computing power isn't really a problem here

we use Jenkins with the XCode plugin

My arguments were that if you build at each commit, you can see right now what went wrong, and correct directly your errors, without bothering the other devs too often. Plus our tester is less bothered by UT errors this way. His arguments were that devs will be flooded by "build error" mails (which is not completely true, as Jenkins can be configured to send a mail only for the first broken build), and that metrics can't be done properly if the frequency of builds is too high.

So, what's your opinion on this ?

答:
Even if you have Jenkins set up to build on a source control commit to a project or any of its dependencies, this does not prevent a developer from deploying to the artifact repository without first committing to source control. If they deploy an uncoordinated API change or a bug in a dependency to the artifact repository, this can break your build without triggering the Jenkins job. I personally would want to know about this ASAP.

Ideally you would build for every commit and also on a schedule to check for situations like I just described. This would conceptually mean you build at least once every 15 minutes.

If you have your Jenkins jobs set up to run on dependency artifact deploys (and if you do...Bravo), you can prob axe the scheduled build if your unit tests are solid (meaning they don't test the dependencies) and your integration/functional tests are not part of the Jenkins job.

As far as the "flood with email" problem, I say getting flooded with email on a broken build is a good thing. Make sure you force developers to respond to the email with a description and you will see your broken builds go way down, trust me.


问:
Sprint Backlog Task Estimates - What Are the Hours Made Of?
For the sprint backlog, I read that the stories are broken into tasks, and estimated.  Are these estimates typically development hours only, or development + QA?  What are these hours typically consisting of?

Thanks.

答:
Assuming there is a story:
As a user i want to login by typing in password.

Possible tasks (assuming two developers - Tom, John):

Design the page - assigned to Tom - 1 hr

Review the page - assigned to Tom - 1 hr

Help Tom reviewing the page - assigned to John - .5 hr

code model - assigned to John - 2 hr

write unit test for model - assigned to John - 2 hr.

Review model code - assigned to Tom - 1 hr

code acceptance test for login page - assigned to Tom - 3 hrs

so on.....


答:
UML emerged out of the "Bubble Wars" of the late 80s and early 90s. It was always a compromise for notation, not a design method. Many of the calumnies attributed to UML are secretly the result of a design method that says "Step 1: draw a class model."

I suggest that we don't need new design methods as much as we should revitalize some old ones. Start with defining and allocating responsibilities, then move to understanding their implementations, and follow with good notations and representations to communicate those ideas.

Responsibilities

CRC works as well for Scala as it does for any other OO language, which is to say that it works very well! Modeling the allocation of responsibilities by anthropomorphizing actors and understanding their collaborations still works well.

At a large scale, you should still be designing with objects. Object boundaries are encapsulation boundaries. Keep mutable state and implementation details inside those object boundaries. Case classes make good interface objects, so do vanilla collections and data structures.

Understanding implementations

Pass these data structures across object boundaries rather than other objects, and you'll find a) it's easier to keep an object's guts hidden inside, and b) functional implementations of object behaviors make a lot of sense.

You won't want to treat the large scale structure of your program as "a vast pool of small functions". Instead, you'll naturally gravitate toward narrow interfaces between isolated parts of the system. These look and feel a lot like objects anyway, so go ahead and implement them as objects!

Representation and Notation

So, within this design structure, you still need to get the thoughts out of your head and share them with someone else.

I suggest that UML can still be useful for describing the large-scale structure of your system. It will not help at the lower levels of detail, though.

At the fine grain of detail, try literate programming techniques.

I also like using minidocs. A minidoc is a one or two page document describing some specific facet of system behavior. It should sit near the code so it gets updated, and it should be short enough to enable just-in-time learning. It takes some practice to hit the right level of abstraction: it needs to be specific enough to be useful but not so specific that it gets invalidated by the next code change.

Title: Re-inventing system design for Scala


问:
How can I translate ML code to F#?
Recently I found a book, Purely Functional Data Structures and all the examples in this book are given in ML with Haskell versions in its appendix. But I only know one programming language with the functional paradigm: F#. And after a bit of research, I found out that F# is (or was) the .NET port of CAML, which is derived from ML. I've heard it mentioned that CAML is just a dialect of ML.

Given that, is it possible to translate ML to F# without a lot of knowledge of ML? What are the key differences from the languages? Or is my best bet to just learn ML instead?

答:
Given that, is it possible to translate ML to F# without a lot of knowledge of ML?

I would say not possible in this (extreme) case.

What are the key differences from the languages?

The big difference in this context is that F# doesn't have anything like ML's module system. Not only does F# not have a higher-order module system (that Okasaki uses extensively to good effect for abstraction, composition and bootstrapping) it does not even have hierarchical modules which means it is abstraction poor in comparison. You can use .NET's OOP but OOP is seriously lame compared to ML's module system.

Or is my best bet to just learn ML instead?

I would recommend learning about ML's module system if you want to understand that half of Okasaki's book. Otherwise, you can translate the low level code (not the powerful abstractions) from ML to F# in order to learn about the guts of purely functional data structures.

Title: How can I translate ML code to F#?


问:
What advantages does developing applications for smartphones have over developing the same application as a web application?
Let's take the Facebook application as an example. Why did they develop an application when the users could just access to their page and do the same? For me that represents more maintenance and more cost because for each feature added to the web application that feature will have to be added to the smartphone application as well.

So why would I want to develop more than once (for each patform iOS, Android, etc) when I could just have one web application? What benefits do I get? The only one that comes to my mind is GPS feature.

EDIT:

My question is more oriented towards business applications that are going to be used only by some members of the company, it's not about selling the application (private use). So contrary to what some answers say about that by developing as a smartphone application it will benefit from more sells because of the "smartphone stores" for me this point is not important because the application is for private use.

By developing the application as a web application it means that it can be accessed through smartphone browser and also in a PC (any capable browser), but developing as a native application would limit this to only some kind of smartphone so we would be limiting  the use.  On the other hand developing it as a web application means that in order to access the application an Internet connection must be available.

So keeping this in mind how would you convince your boss to write the application for a given smartphone platform (iOS/Android) vs developing it as a web application?

答:
Considering your constraints (private business application, for usage by some members of the company), I say you have two main approaches to convince your boss to develop a mobile application vs web application:

1) A mobile version could be more suitable for your case, given the possibility to do some work offline, GPS capabilities to know your location, ability to work from home, public transports or anywhere (people carry their smartphone much more often than their laptop). I know this goes in line with many of the comments already put here, but without knowing the actual business application you are talking about, it pretty much comes down to this: either a mobile version has the potential to be much more practical to use, in order to counterbalance the fact that you are spending resources on a more restricted platform, or it does not.

2) Is the company any interested in future mobile developments? If yes, then by developing an internal mobile application you give the employees more experience, get them to try new technologies, and another tool gets added to the company with the potential to generate revenue. All in the relative "safe" environment of a simple, but useful internal application, that will be used by some people within the company, which will also provide their comments and feedback.

So to summarize: you have to demonstrate that a mobile version will generate more revenue, either in short term, by making the employees that will use the application more efficient and flexible, or in longer terms, by giving employees a new/broader knowledge that has possibilities for the future (or possibly, both). It will also depend on how good is the company at the moment, how much money they are making, and how much experienced people do you have available that could develop it in an acceptable time.

Hope it helps :). I know it is all very subjective, but it is hard to provide more reasons without some concrete application/domain.


答:
Yes.  This is acceptable.

Making all actors a subclass of "User" is needless.  That goes without saying.

The original Objectory method (on which UML is based) explicitly makes the case that "Actor" is a kind of classifier, and has subclasses and superclasses.

Don't go crazy however.  The inheritance among users should be kept quite simple.

Title: Use Case Structure

Body:
I am creating use cases for a project.  A generic user is extended by user "categories" which then is extended by an administrator (that can do all tasks possible).

Is the following acceptable to portray? Is there a better way to portray such info?


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答:
Point 1, NO! Studio is meant to be run on decent machines and that requirement has only become more powerful with each version.  You can actually lock some versions of studio if you turn intellisense on and use a single core non HT box.

To point #2 there are some features in the testing projects that allow you to throttle some resources.  They are not perfect, but they are there.  VPC or low spec VM images to a pretty good job of being constrained as well.  I have had users sit down at bad machines to do testing occasionally so that they can see the implications of the features they have requested.


问:
Is CSS resizing of images still a bad idea?
It's always been looked at that using width/height attributes on images which aren't what the original image actual is is a bad idea. It could mean pixalated images or download sizes bigger than nessary.

But, is this still an issue? I wouldn't suggest up-sizing photos, but downsizing shouldn't be an issue provided that its not too much of a difference from the original and keeping to scale.

For example, I have a photo that is 600x400 and I stick a width of 400px on it. Most modern browser scale the image down and it looks like rendering is still decent.

So, what is everyones view on this?

答:
The issue is the payload, the browser will render is just about fine in any size (esp smaller sizes that you are talking about)

For a high volume site, even single bytes matters. You don't want to send unwanted data.

Speaking of bad Idea, it is not really a bad idea to adjust the width/height by a few pixels or may be 10 or 20 pixels. But it is a very bad idea if you are shrinking a large image to a thumbnail :)


答:
Imagine a piece of code for drawing on a form

```<code>{
  Point p = textBox1.Location;
  Size dp = textBox1.Size;

  // Here the + operator has been overloaded by the CLR
  p += dp;  // Now p points to the lower right corner of the textbox.
  ..
}
</code>```

Another common example is when a structure is used to hold position information in the form of a vector.

```<code>public struct Pos
{
    public double x, y, z;
    public double Distance { get { return Math.Sqrt(x * x + y * y + z * z); } }
    public static Pos operator +(Pos A, Pos B)
    {
        return new Pos() { x = A.x + B.x, y = A.y + B.y, z = A.z + B.z };
    }
    public static Pos operator -(Pos A, Pos B)
    {
        return new Pos() { x = A.x - B.x, y = A.y - B.y, z = A.z - B.z };
    }
}
</code>```

only to be used later as

```<code>{
    Pos A = new Pos() { x = 4, y = -1, z = 0.5 };
    Pos B = new Pos() { x = 8, y = 2, z = 1.5 };

    double x = (B - A).Distance;
}
</code>```

Body:
Imagine a piece of code for drawing on a form

{
  Point p = textBox1.Location;
  Size dp = textBox1.Size;

  // Here the + operator has been overloaded by the CLR
  p += dp;  // Now p points to the lower right corner of the textbox.
  ..
}

Another common example is when a structure is used to hold position information in the form of a vector.

public struct Pos
{
    public double x, y, z;
    public double Distance { get { return Math.Sqrt(x * x + y * y + z * z); } }
    public static Pos operator +(Pos A, Pos B)
    {
        return new Pos() { x = A.x + B.x, y = A.y + B.y, z = A.z + B.z };
    }
    public static Pos operator -(Pos A, Pos B)
    {
        return new Pos() { x = A.x - B.x, y = A.y - B.y, z = A.z - B.z };
    }
}

only to be used later as

{
    Pos A = new Pos() { x = 4, y = -1, z = 0.5 };
    Pos B = new Pos() { x = 8, y = 2, z = 1.5 };

    double x = (B - A).Distance;
}


答:
It results in a bunch of bitchin' developers. This stuff is hard enough as it is, let's not make the experience worse.

I would encourge you to have similar hardware to your users in a Test or QA environment to smoke out any performance issues however. That's a good idea.

Title: Does giving a developer a slower development machine result in faster/more efficient code?

Body:
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards


问:
How do you handle minor change in source code causing discontinuity in version tree?
For instance, I have a file with poor indentation (at least incoherant with the rest of the project).

If I correct the indentation and commit, there will be a serious change in the file at a certain point in time, causing the diffs between versions before and after that serious change to be hard to read.

How do you handle that king of minor logical modification causing major diffs ?

答:
You need to do it, so do it.

However, isolate it to that commit. Make one commit fixing the whitespace and making no other changes to the code. That will be easiest to work with later if you need to revise the repo history or bisect, etc.


问:
What is the optimal minimum time to work on tasks for a single project?
As I'm getting more organized, and getting more projects, I'm starting to wonder how to best manage time between them.  Especially in regard to how I give estimates to the PHBs.

So if the project is broken up into small tasks, say 2-3 hours each, then is it just as productive to work on one task per day as opposed to spending 6 hours a day and working through a good portion of 3 tasks.

I realize that to a certain extent this depends on the project, but I also think that it might be better in general to work on components together so that things stay fresh in your mind.

That said, it means pushing back other projects a week or two in order to devote 6 hours a day towards those tasks.

Just trying to think this through, and thought I'd get some input.

答:
I think the best way to breakup tasks is to split them into small tasks 1-3 hours a piece. This way you can focus on completing small pieces without interruption (hopefully). Ideally you can work on multiple small tasks from the same project all in a row, this saves you the context switch. Unfortunately, we don't all work in an ideal setting (in fact most of us don't).

Managing the tasks is a matter of assigning priority to them. This is how I do it, in descending order of importance.

Order of dependency. Obviously some tasks have to be done before others, do those first.

What the boss/client wants done first. Once you know which tasks need to be done first, you can figure out which tasks you need to do to satisfy this requirement.

Tasks that free up other to complete work on the project. This helps keep things moving, its not always the most optimal for you, but you work in a team with other programmers, testers and clients. If 6 people are waiting for you to complete one task and 3 people are waiting for you to complete another task, do the task for the 6 people.

Related Tasks. Group related tasks to avoid context switches and get things done faster.

Summary
Always break your tasks down into small units. An hour of work is ideal. Complete your tasks in an order that allows the projects to be completed as quickly as possible. This has the side effect of decreasing the number of active projects you have at once, which is a good thing - though it usually just means your boss gives you more.


问:
What has research shown about the effectiveness of comments?
I have been arguing with a friend about the necessity of comments, and the efficiency of different comment styles. The argument ended quite fast, as we could not find any research - or essay - that support either claim.

Has any serious research been conducted regarding the efficiency of different commenting styles? If so, what has it shown? I'm mainly interested with:

Length (I think that comments longer than a tweet are never read)

Type (I strongly favor comments that are actual code samples, explaining how to call a method)

Location (As a separate line? at the end of the line?)

答:
There may be some research but I would take it with a large pinch of salt. Good comments are hard to define and very situational, its like asking for research on how good books are based on the length of the words or the number of pages.

Good comments are an art form.

On a side note I suggest you read code complete. Its a great guide for how to write good comments.


问:
What languages are used by professional mobile app designers?
I've recently done some Java programming for an android app (though my question is not android specific), and was wondering if what I was doing was just a lot less complicated, but generally the same as what a professional mobile app designer would do.

I kind of asssumed that an app designer working for, say, the BBC would use an expensive software package, and maybe a different language.

So my question is what language would they be using? Maybe they would use one that would work for both Android and iOS?

答:
Barring things like SL4A, all android apps are written in Java, and iOS apps can be written in several languages

Android runs all software on the Dalvik VM, which is an alternative java implementation that strips down some things not appropriate for the system. Android apps are compiled to normal java bytecode and interpreted on the device.

I don't have any experience on iOS architecture beyond the language they use, but I would assume it's something similer. (Someone who does know, feel free to edit that information into here).


问:
Addressing a variable in VB
Why doesn't Visual Basic.NET have the addressof operator like C#? In C#, one can

```<code>int i = 123;
int* addr = &i;
</code>```

But VB has no equivalent counter part. It seems like it should be important.

UPDATE Since there's some interest, Im copying my response to Strilanc below.

The case I ran into didnt necessitate
  pointers by any means, but I was
  trying to trouble shoot a unit test
  that was failing and there was some
  confusion over whether or not an
  object being used at one point in the
  stack was the same object as an object
  several methods away.

答:
The AddressOf operation serves to declare a delegate (event handler) from a method. Like this:

```<code>Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim handler As EventHandler = AddressOf ButtonClickHandler
End Sub

Public Sub ButtonClickHandler(ByVal sender As Object, ByVal e As EventArgs)
    ...
End Sub
</code>```

without it VB.NET would try to call the method instead of just referencing its location. In C# this is not needed because ButtonClickHandler refers to the address of the method and ButtonClickHandler() calls the method. In VB.NET you can omit the parenthesis on a function and still be called. It is part of the crazyness of VB.NET trying to look like VB6 and feel like C# at the same time.

Title: Addressing a variable in VB

Body:
The AddressOf operation serves to declare a delegate (event handler) from a method. Like this:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim handler As EventHandler = AddressOf ButtonClickHandler
End Sub

Public Sub ButtonClickHandler(ByVal sender As Object, ByVal e As EventArgs)
    ...
End Sub

without it VB.NET would try to call the method instead of just referencing its location. In C# this is not needed because ButtonClickHandler refers to the address of the method and ButtonClickHandler() calls the method. In VB.NET you can omit the parenthesis on a function and still be called. It is part of the crazyness of VB.NET trying to look like VB6 and feel like C# at the same time.


问:
How do I refer to the smallest possible non-zero value?
Back in my C programming days I thought there was a constant or function (I can't remember what it was called, let's call it SMALL) whose value was the smallest possible positive value. (Imagine the LSB=1 and all other bits = 0.) It was used to avoid a divide by zero error.

For example,  let's say you want to compute z = x/y. Then you could calculate

z = x / (y + SMALL);

Is there a built-in function in MS EXCEL that implements SMALL? For that matter, does it exist in C/C++ or am I going crazy?

答:
Take a look at http://www.cplusplus.com/reference/clibrary/cfloat/ the FLT_EPSILON can be used to compare a float variable to 0 (zero), or nearly zero in that case.

There's an other article here: http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm

EDIT: what you need is this q&a: https://stackoverflow.com/questions/9380108/get-machine-epsilon-in-microsoft-excel it describes the epsilon value in excel.


答: For android I use Java, and for ipad and iphone people use Objective-C. I think the big picture here is java, not because of android, but blackberry and other SDKs like Samsung is developed by Java. And JavaME was also big one before the android. And there is hybrid applications done with HTML5, CSS, JS. For example http://phonegap.com/</p>

Title: What languages are used by professional mobile app designers?

Body:
I've recently done some Java programming for an android app (though my question is not android specific), and was wondering if what I was doing was just a lot less complicated, but generally the same as what a professional mobile app designer would do.

I kind of asssumed that an app designer working for, say, the BBC would use an expensive software package, and maybe a different language.

So my question is what language would they be using? Maybe they would use one that would work for both Android and iOS?


答: As @Rythal said its a terrible way of avoiding divide by zero, however, if you wish to persist, the minimum (and maximum) values for float and double are defined in float.h. This is explored here. </p>

Title: How do I refer to the smallest possible non-zero value?

Body:
Back in my C programming days I thought there was a constant or function (I can't remember what it was called, let's call it SMALL) whose value was the smallest possible positive value. (Imagine the LSB=1 and all other bits = 0.) It was used to avoid a divide by zero error.

For example,  let's say you want to compute z = x/y. Then you could calculate

z = x / (y + SMALL);

Is there a built-in function in MS EXCEL that implements SMALL? For that matter, does it exist in C/C++ or am I going crazy?


答:
I think you're probably remembering FLT_EPSILON, DBL_EPSILON, and so on.

They aren't quite what you're describing though: they're not the smallest number greater than 0. Rather, they're the smallest number greater than 1. For better or worse, however, DBL_EPSILON-1 won't be even close to the smallest number greater than 0. Epsilon is really intended to be scaled by multiplication, not addition or subtraction.

This is not normally used to avoid problems with division by zero, but to give some idea of the smallest possible difference between two numbers, and whether two numbers are "substantially different", or any inequality between them is really due to rounding errors (and such).

I'd also note that replacing x/y with x/(y+EPSILON) could quite easily cause a division by zero rather than preventing it (i.e., if y == -EPSILON).


答:
There are frameworks/toolkits out there that allow you to develop cross-platform for various mobile platforms, in various languages.

For example, Xamarin's MonoTouch is a framework that allows you to write an app in C# and then build an application for iOS or Android. It's also the only cross-platform kit I know of that allows you to share code for iOS, Android, and Windows Phone.

Corona lets you use Lua, a scripting language, but I think it supports Android and iOS only.

A more specialized platform is Unity, which allows you to use Boo, C#, or an EMCAScript-based (think Javascript) language to build games and target Android, iOS, as well as web browsers and console systems.

If you stick with being platform-specific, the main way to write apps for iOS is Objective-C, though you can also use Objective C++.

On Android, you can write applications in a JVM language like Java, but you can also alternatives like Scala or Clojure if that floats your boat. You can also go native on those respective platforms. Android, for example, provides the Native Development Kit, which allows you to write apps with native code.

For Windows Phone 7, you can use a CLR language. This primarily means C#, but you could also use a more exotic language, like F#.


答:
The proper C++ way is in the <limits> header:

in particular std::numeric_limits<T>::epsilon() is defined (specialized) for all the built-in types as in cppreference


答:
I will handle it in this way:

Make one commit ONLY involving the indentation correction

Define a label to categorize this kind of "minor logical modification causing major diffs" behaviors (e.g. [CodingStandard]), and include such label in the comment on that commit (e.g. [CodingStandard] Correct the indentation)

Item 2 is for your convenience when you want to quickly browse the log of the commits. Item 1 makes it easier to verify whether the commit does exactly what the comment suggests.

Now, let's say you have 5 commits for this file:

```<code>            [CodingStandard]
                 |
                 V
 X1 <--- X2 <--- X3 <--- X4 <--- X5
</code>```

It doesn't help you if you intend to diff X1 and X5. However, it gives you a chance to isolate diff(X2,X3) out that you just need to study diff(X1,X2) and diff(X3,X5).

Title: How do you handle minor change in source code causing discontinuity in version tree?

Body:
For instance, I have a file with poor indentation (at least incoherant with the rest of the project).

If I correct the indentation and commit, there will be a serious change in the file at a certain point in time, causing the diffs between versions before and after that serious change to be hard to read.

How do you handle that king of minor logical modification causing major diffs ?

Body:
I will handle it in this way:

Make one commit ONLY involving the indentation correction

Define a label to categorize this kind of "minor logical modification causing major diffs" behaviors (e.g. [CodingStandard]), and include such label in the comment on that commit (e.g. [CodingStandard] Correct the indentation)

Item 2 is for your convenience when you want to quickly browse the log of the commits. Item 1 makes it easier to verify whether the commit does exactly what the comment suggests.

Now, let's say you have 5 commits for this file:

            [CodingStandard]
                 |
                 V
 X1 <--- X2 <--- X3 <--- X4 <--- X5

It doesn't help you if you intend to diff X1 and X5. However, it gives you a chance to isolate diff(X2,X3) out that you just need to study diff(X1,X2) and diff(X3,X5).


问:
Can commits be considered too small?

Possible Duplicates:

  git / other VCS - how often to commit?

  How often should I/do you make commits?

The usage of source control is very different from one developer to another and from project to another. Some commit very often; others can spend a whole day or several days without committing (especially when they work on the project alone or they know that other team members are working on very different part of the project).

Examples

Sometimes, I've seen extremely small commits, both in real life and in webcasts and other learning material. Some examples, mostly from real life, are:

A commit which solves a bug #... or implements a feature #... by changing one line of code.

IMHO, it's a perfectly valid case for a commit, especially if the bug tracking system is linked to the version control and is updated automatically according to the revisions. Even without this link, it's useful to track which commit solved what, independently of the number of changes required to solve a bug or implement a feature.

A commit which changes a single configuration setting (given that in the context, configuration settings must be in source control).

IMHO, this could be merged sometimes with another commit, unless the previous setting breaks the build or introduces a bug or can affect other developers (for example a connection string which changed after the test database server was migrated).

A commit which corrects spelling of a word, for example in a string displayed to the user.

IMHO, in most cases, this can be merged with another commit (unless, again, it breaks the build). The only case where it cannot be merged is when, if left, the wrong spelling can be propagated through code and would be too complicated or impossible to change later, as with HTTP referer header.

A commit which adds a comment to a method (while the method was already explicit enough) or solves another minor style-related rule.

Example: in .NET Framework, StyleCop requires to document every method, and the XMLDoc comment for a constructor (which is method too) must begin with:

Initializes a new instance of the <Class name here> class.

A commit can enforce this last rule, replacing a comment in legacy code:

Creates a new vehicle with the specified number of wheels.

by:

Initializes a new instance of the Vehicle class, using the specified number of wheels.

In other words, the revision has no meaning other than to conform the piece of code to the style standards used in the codebase.

IMHO, this can be merged with another commit in every case (after all, style-related rules must be enforced at commits to reject the commits of the code which doesn't match them), unless there are several changes in several places.

Questions

Am I wrong on those points?

Is there such a thing as a commit too small, or is a practice of committing very often a best practice?

Does it worth it to commit too small changes, given that it would "pollute" the revision log and make it more difficult to find the relevant changes among tiny changes nobody cares about and which don't break or unbreak the build, nor affect other developers?

答:
First of all, I don't think there is one answer to this question. As you point out, it differs a lot between individuals and projects.

I apply something like the idea of SoC (Separation of Concerns) to commits. That is, I try to commit on a "per task" basis. Or, in other words, avoid committing "several areas of work" at once. In that sense, there is no such thing as a commit too small.

Title: Can commits be considered too small?


问:
Not-for-profit universities that offer computer science undergraduate degree online?
There are many masters degree programs in computer science online offered by reputable organizations. However, I've found very few bachelors only degree programs offered by non for-profit institutions.

I am looking for a degree in computer science and also any programs for entrepreneurship/management or algorithmic trading.

I've found only 2 programs so far that fit:

http://www.regis.edu/regis.asp?sctn=cpcis&p1=ap&p2=cs&p3=ol

http://depaul.edu

Requirements:

100% online undergraduate non-profit

Options: Bachelor of Science Bachelor of Arts

Bonuses: accelerated recognized ABET cost effective

Update:
I've answered my question with a list. If anyone knows an online program that combines skills in entrepreneurship (getting capital, starting a business) or algorithmic trading with a computer program that would be ideal.. maybe too much to ask though

答:
I got mine from University of Maryland University College. http://umuc.edu/

UMUC is part of the Maryland state university system and is a public institution. Their computer science program is pretty good and entirely online.

UMUC is also regionally accredited by the US Dept. of Education. http://umuc.edu/gen/accred.shtml


答:
Wrong is too strong a word, because this is a matter of style/preference. However, my preference is apparently diametrically opposed to yours.

I much prefer seeing coding style edits and small documentation changes done in their own commits. If I'm doing a code review, or trying to figure out where a bug was introduced, it's much easier if each commit doesn't touch on half a dozen random issues. In my world an ideal commit fixes one bug, or completes one feature. That way if the fix or new feature turns out to have some serious problem, backing it out is much easier: you don't have to try and untangle a grab-bag of changes unrelated to the problem.

Now, if you have a batch of changes that are documentation/formatting issues only, feel free to bundle those together, and your commit comment should indicate "Formatting/documentation changes only".

Title: Can commits be considered too small?

Body:
Possible Duplicates:

  git / other VCS - how often to commit?

  How often should I/do you make commits?

The usage of source control is very different from one developer to another and from project to another. Some commit very often; others can spend a whole day or several days without committing (especially when they work on the project alone or they know that other team members are working on very different part of the project).

Examples

Sometimes, I've seen extremely small commits, both in real life and in webcasts and other learning material. Some examples, mostly from real life, are:

A commit which solves a bug #... or implements a feature #... by changing one line of code.

IMHO, it's a perfectly valid case for a commit, especially if the bug tracking system is linked to the version control and is updated automatically according to the revisions. Even without this link, it's useful to track which commit solved what, independently of the number of changes required to solve a bug or implement a feature.

A commit which changes a single configuration setting (given that in the context, configuration settings must be in source control).

IMHO, this could be merged sometimes with another commit, unless the previous setting breaks the build or introduces a bug or can affect other developers (for example a connection string which changed after the test database server was migrated).

A commit which corrects spelling of a word, for example in a string displayed to the user.

IMHO, in most cases, this can be merged with another commit (unless, again, it breaks the build). The only case where it cannot be merged is when, if left, the wrong spelling can be propagated through code and would be too complicated or impossible to change later, as with HTTP referer header.

A commit which adds a comment to a method (while the method was already explicit enough) or solves another minor style-related rule.

Example: in .NET Framework, StyleCop requires to document every method, and the XMLDoc comment for a constructor (which is method too) must begin with:

Initializes a new instance of the <Class name here> class.

A commit can enforce this last rule, replacing a comment in legacy code:

Creates a new vehicle with the specified number of wheels.

by:

Initializes a new instance of the Vehicle class, using the specified number of wheels.

In other words, the revision has no meaning other than to conform the piece of code to the style standards used in the codebase.

IMHO, this can be merged with another commit in every case (after all, style-related rules must be enforced at commits to reject the commits of the code which doesn't match them), unless there are several changes in several places.

Questions

Am I wrong on those points?

Is there such a thing as a commit too small, or is a practice of committing very often a best practice?

Does it worth it to commit too small changes, given that it would "pollute" the revision log and make it more difficult to find the relevant changes among tiny changes nobody cares about and which don't break or unbreak the build, nor affect other developers?


答:
I don't think any commit could be too small as long as the comment is accurate; lack of or misleading commit comments are reprehensible.

Personally I prefer to commit changes in logical groups, e.g. one commit for refactoring before making any logical changes, then another for changes to fix the bug.

I also prefer comments to contain some detail, so I'll look through all files that have changed in order to gather related changes that can be covered by the same comment, separating those that need some detail that doesn't apply to other files.

Title: Can commits be considered too small?


答: Small commits are great. IMHO, the smaller the better. In particular, small commits are good because they are easily reviewable. I would rather review 5 small independent changes than 1 larger change that incorporates them all.</p>

Title: Can commits be considered too small?


问:
Examples of operator overloading, which make sense
While I learning C#, I found that, the C# supports operator overloading. I have problem with good example which:

Make sense (ex. adding class named sheep and cow)

Is not an example of concatenation of two strings

Examples from Base Class Library are welcome.

答:
I'm surprised nobody mentioned one of the more interesting cases in BCL: DateTime and TimeSpan. You can:

add or subtract two TimeSpans to get another TimeSpan

use unary minus on a TimeSpan to get a negated TimeSpan

subtract two DateTimes to get a TimeSpan

add or subtract TimeSpan from a DateTime to get another DateTime

Another set of operators that could make sense on a lot of types are <, >, <=, >=. In the BCL, for example Version implements them.