问:
To Domain or not to Domain
The SQL92 and SQL99 standards define CREATE DOMAIN DDL constructs. Not all databases support this, or have a different name for it (SQL Server has User Defined Types, for example).

These allow one to define a constrained data-type to be used in their database, to simplify and enforce rules pertaining to the allowed values. Such a data-type could be used in column declarations, in inputs and outputs to stored procedures and functions etc...

I would like to know:

Do people actually use domains in their database designs?

If so to what extent?

How useful are they?

What pitfalls have you encountered?

I am trying to asses the viability of using these in future database development.

答:
As a user of SQL Server and C#, I haven't used User Defined Types in database, since I'm pretty more powerful in application side. Event after ORMs like LINQ to SQL and Entity Framework, my use of server capabilities has reduced a lot.

For example, I was using CLR integration to load some DateTime conversion functions to SQL Server to transfer Gregorian date-times into other formats, based on the Globalization power of .NET. But now, things are different, and I don't do that anymore. I simply load the data, and do the transformation, right in my application layer.

So, after almost 4 years of programming and inspecting all the teams I can think of, I've found no sample of using User Defined Types. I also haven't seen it in action in many .NET blogs.

While this doesn't mean that people don't use Database Domain, it surely means that at least using Database Domain is not that common.

Title: To Domain or not to Domain


答:
There are already a detailed answer on Stack Overflow. I mostly agree with it, but not with the given example, I quote:

“For example, I define a "GenderType" (char(1), not nullable, holding "M" or "F") that ensures that only appropriate data is permitted in the Gender field.”

Personally, I feel more comfortable setting char(1) type and defining a constraint on the column. When the constraint is violated, I know exactly where to search to find what I did wrong. It's also more known than user defined types, so the database which uses only constraints would be easier to understand for a beginner.

Of course, just is just a personal opinion. Other people would say that an in ('M', 'F') constraint is not self-documenting and may be very obscure for a fresh developer who discovers the database.

IMO, use user defined types for more complicated types, and constraints for something basic. Also, when you cannot find easily an explicit name for a type, there is a chance that a constraint will fit better.

ContentLicense: CC BY-SA 3.0

Title: To Domain or not to Domain

Body:
The SQL92 and SQL99 standards define CREATE DOMAIN DDL constructs. Not all databases support this, or have a different name for it (SQL Server has User Defined Types, for example).

These allow one to define a constrained data-type to be used in their database, to simplify and enforce rules pertaining to the allowed values. Such a data-type could be used in column declarations, in inputs and outputs to stored procedures and functions etc...

I would like to know:

Do people actually use domains in their database designs?

If so to what extent?

How useful are they?

What pitfalls have you encountered?

I am trying to asses the viability of using these in future database development.


问:
When is it preferred to combine Add/Edit functionality, and when to keep them separate?
I regularly come across situations where I need to Add or Edit an item, and sometimes I use separate methods for Add and Edit, and other times I combine them into a single method.

Is one method preferred over the other? If so, why?

```<code>public void AddItem()
{
    ShowEditingPopup(new Item(), "Add Item");
}

public void EditItem(Item item)
{
    ShowEditingPopup(item, "Edit Item");
}
</code>```

OR

```<code>public void EditItem(Item item)
{
    ShowEditingPopup(
        (item ?? new Item()),
        string.format("{0} Item", (item == null ? "Add " : "Edit "))
    );
}
</code>```

where ShowEditingPopup is defined as

```<code>public void ShowEditingPopup(object popupDataContext, string popupTitle)
{
    PopupDataContext = popupDataContext;
    PopupTitle = popupTitle;
    IsPopupVisible = true;
}
</code>```

Edit: Just to clarify, I am not Saving the item, I am opening it for Editing. I almost always implement a generic Save method for saving to the database

Edit #2: Edited code samples so they more accurately reflect the sort of situation I am referring to

答:
I personally tend to follow the principals of being semantic. This means that I usually don't provide a all-in-one edit form. In other words, users usually don't want to edit the entire information of an entity. Rather their edit process is more semantic and can be classified. For example, for user entity, people usually edit passwords and edit profile. Thus, I make two functions for edit like:

```<code>public bool EditPassword(string userName)
{
    // code here
}

public bool EditProfile(Profile newProfile)
{
    // code here
}
</code>```

Or, users usually edit an article in these ways:

```<code>public bool PutArticleIntoCategories(int articleId, List<Category> categories)
{

}

public bool EditArticleSummary(int articleId, string newSummary)
{

}
</code>```

In brief, I usually create a all-in-one creation form, but I tend to use small, chunked edit forms for each semantic edit operation. Thus, I usually don't merge them. However, this doesn't mean that you can't merge them. Whenever you want to provide a fat, big edit form which resembles creation form, I think merging can work better.

Body:
I personally tend to follow the principals of being semantic. This means that I usually don't provide a all-in-one edit form. In other words, users usually don't want to edit the entire information of an entity. Rather their edit process is more semantic and can be classified. For example, for user entity, people usually edit passwords and edit profile. Thus, I make two functions for edit like:

public bool EditPassword(string userName)
{
    // code here
}

public bool EditProfile(Profile newProfile)
{
    // code here
}

Or, users usually edit an article in these ways:

public bool PutArticleIntoCategories(int articleId, List<Category> categories)
{

}

public bool EditArticleSummary(int articleId, string newSummary)
{

}

In brief, I usually create a all-in-one creation form, but I tend to use small, chunked edit forms for each semantic edit operation. Thus, I usually don't merge them. However, this doesn't mean that you can't merge them. Whenever you want to provide a fat, big edit form which resembles creation form, I think merging can work better.


问:
Writing robust code vs. overengineering
How do you guys know that you are writing the most robust code possible without overengineering?

I find myself thinking too much about every possible path that my code can take, and it feels like a waste of time sometimes. I guess it depends on the kind of program you are writing, but I don't want to use too much of my time taking situations into account that will never happen.

答:
Robustness: The degree to which a system continues to function in the presence of invalid inputs or stressful environmental conditions. (Code Complete 2, p464)

The important question here is to ask how important robustness is to you. If you are Facebook, it is really important that your website continue to function when someone puts special characters in the input, and that your server stay up when 100million users are logged on simultaneously. If you are writing a script to perform a common operation that only you do, you don't care much.  In between there are lots of levels. Making a judgement as to how much robustness you need is one of the important skills a developer should learn.

The principle of YAGNI applies to adding features that a program might need. But that principle doesn't apply to robustness. Programmers tend to overestimate the likelihood that a given future extension will be needed (especially if its a cool one) but they underestimate the likelihood of things going wrong. Also, if it turns out that an omitted feature is needed after, the programmer can write it later. If it turns out an omitted error check is needed after all, the damage may be done.

Therefore it is actually better to err on the side of doing the checks for unusual error conditions. But there is a balance. Some of the things to consider in this balance:

How often might this error occur?

What is the cost of having this error happen?

Is this for internal or external use?

Don't forget that people can - and will - try to use your program in unexpected ways. It's better if something predictable happens when they do.

As a last line of defense, use the assert or the shutdown. If something happens which you can't work out how to deal with it, shut down the program. That is usually better than allowing the program to go on and do something unpredictable.

Title: Writing robust code vs. overengineering


问:
How granular should TDD tests be?
During TDD training based on medical software case we are implementing the following story: "When user presses Save button, system should add patient, add device and add device data records".

The final implementation will look something like this:

```<code>if (_importDialog.Show() == ImportDialogResult.SaveButtonIsPressed)
{
   AddPatient();
   AddDevice();
   AddDeviceDataRecords();
}
</code>```

We have two ways to implement it:

Three tests where each verifies one method (AddPatient, AddDevice,     AddDeviceDataRecords) was called

One test which verifies all three methods were called

In the first case if something wrong is happend to if clause condition, all three tests will fail. But in the second case if test fails, we are not sure what is exactly wrong. What way would you prefer.

答:
We write our unit tests for meaningful sentences of functionality which many times map to a method (if you've written your code well), but sometimes get bigger, encompassing many methods.

For example, imagine that adding a patient to your system needs some subroutines (child functions) to be called:

VerifyPatientQualification

EnsureDoctorExistence

CheckInsuranceHistory

EnsureEmptyBed

We might also write unit test for each of these functions.

Title: How granular should TDD tests be?


问:
Real world pitfalls of introducing F# into a large codebase and engineering team
I'm CTO of a software firm with a large existing codebase (all C#) and a sizable engineering team.  I can see how certain parts of the code would be far easier to write in F#, resulting in faster development time, fewer bugs, easier parallel implementations, etc., basically overall productivity gains for my team.  However, I can also see several productivity pitfalls of introducing F#, namely:

1) Everyone has to learn F#, and it's not as trivial as switching from, say, Java to C#.  Team members that have not learned F# will be unable to work on F# parts of the codebase.

2) The pool of hireable F# programmers, as of now (Dec 2010) is non-existent.  Search various software engineer resume databases for "F#", way less than 1% of resumes contain the keyword.

3) Community support as of now (Dec 2010) is less available.  You can google almost any problem in C# and find someone that has already dealt with it, not so with F#.  Third party tool support (NUnit, Resharper etc) is also sketchy.

I realize that this is a bit Catch-22, i.e. if people like me don't use F# then the community and tools will never materialize, etc.  But, I've got a company to run, and I can be cutting edge but not bleeding edge.

Any other pitfalls I'm not considering?  Or anyone care to rebut the pitfalls I've mentioned?  I think this is an important discussion and would love to hear your counter-arguments in this public forum that may do a lot to increase F# adoption by industry.

答: I would say the first thing you need to do is ask your team members how they feel about introducing F#. If they like the idea, everything will go much smoother then if they don't.</p>

OwnerDisplayName: nganju


答:
I have not used this feature myself but I guess you need to make sure that:

If your database is used by a single system, it may make sense not to use this feature and add the check logic in your business layer or its equivalent. That will give you more flexibility in validation (say in using regular expressions) and will make it possible to encapsulate all the validation logic in one place. If your database is shared by several systems, you may instead use triggers which are well suited for this task.

I am not sure if UDT allows you to customize the error messages returned to the client when a validation error is encountered.

UDTs are very useful if the same validation rule applies to several columns. In my opinion, I don't see this as a very common case in business application with normalized database design.

You may be interested in checking "What's the Point of [SQL Server] User-Defined Types?" blog article.

Title: To Domain or not to Domain


问:
What are the consequences of still sticking with Windows XP despite there are Windows Vista, 7 and very soon 8?
From a .Net programmer perspective, what are the consequences of still sticking with Windows XP despite there are Windows Vista, 7 and very soon 8? How does having windows XP limit programmers development in .Net platform?</p>

答:
Fairly soon you will find that the latest versions of programming tools won't run on Win XP, or if they do they will be sub-optimal in some way.

As an example from my website: In just under 3 weeks, out of 850 downloads for a new .NET tool, just 4 were for XP. There's little incentive therefore to keep doing a specific XP build/test. There have been a lot more downloads for the Windows 8 (dev preview) optimised build than for XP and Win 8 has only been out a week. Note: This case isn't quite a fair comparison, because the XP tool version requires an msi installation instead of a .exe which needed no install, this probably deterred some XP users.

The fact that the latest tools won't run optimially on your XP machine, may not be an issue for you There must be a lot of XP users/programmers out there still, but many probably already have the tool set they need.


问:
Is it good or bad form to name a function after the workaround it fixes?
Lets say you have to write some code to fix a bug that on first glance by another engineer would seem weird or unnecessary.

Would it be good or bad form to put the code in a method named for example "preventWindowFromJumpingWhenKeyboardAppears" or just name it "forceSpecifiedWindowPosition" and then add a comment about why you are doing this when calling the method?

答: I tend to think that naming methods should be concise and general with comments filling in the specific details. So I would think your second name is better. But that is just me.</p>


答:
Don't worry about pride -- yours or anyone else's. Don't worry about good form. There is only one thing you should worry about when naming a method: What reads best in the calling code?

What is someone else going to see, when they come back to this code later? Will they see a method which positions a window that was just created, or will they see something that appears to do nothing (thus tempting them to remove it)?

Imagine yourself as a future newbie reading the calling method. You don't want to click through to the method implementation to find anything out, nor do you want to have to go to version control or bug-tracking to find out why something was added, you're just trying to read the flow of that method.

Put exactly as much information in the method name as you would want to read in the calling method and no more.

Title: Is it good or bad form to name a function after the workaround it fixes?

Body:
Lets say you have to write some code to fix a bug that on first glance by another engineer would seem weird or unnecessary.

Would it be good or bad form to put the code in a method named for example "preventWindowFromJumpingWhenKeyboardAppears" or just name it "forceSpecifiedWindowPosition" and then add a comment about why you are doing this when calling the method?


答:
I think it's better to name methods based on what you are trying to accomplish rather than how, as part of the whole public interface / private implementation thing.  So, all else being equal, I would call it "preventWindowFromJumpingWhenKeyboardAppears".

However, all else might not be equal.  Will the parameters make sense equally with both names?  If you have to pass the window position to "forceSpecifiedWindowPosition" it makes sense, but not so much for "preventWindowFromJumpingWhenKeyboardAppears", which sounds like it would either be passed nothing or a window.  Also, if forcing the window position could be considered a side-effect (sounds like no - it's the effect you want) then "preventWindowFromJumpingWhenKeyboardAppears" would have results that might be unexpected from the name, so I wouldn't name it that.


问:
Point and click synonym replacement in text area with Javascript
I am trying to create a site that will allow you to type a sentence or passage of text, then click on words to bring up a list of synonyms (from an online API) and possibly authorized abbreviations from a list that I provide. Once clicked, it would replace that word with the word that was clicked on. It would function kind of like After the Deadline or a Javascript based spell checker.

Are there any libraries set up to make something like this easy, or what kind of Javascript do I need to be looking at? Are there any tutorials or examples for this kind of thing? I am aware that the source code for After the Deadline is available, but I only need a small portion of their technology, not all of the actual grammar and spelling check technology.

答:
JQuery UI Autocomplete has options for auto-completing multiple words, works with whatever data source, is pretty easy to use, and comes from a library a lot of support. </p>

<p>Since the data source is configurable you can do things other than auto complete, such as synonyms.  It doesn't work on click though.  I don't know of anything that works on the click, since users normally would expect the caret to move on click, but if you really want it to work that way you could probably call the same code from the onclick event, more or less. </p>

Body:
JQuery UI Autocomplete has options for auto-completing multiple words, works with whatever data source, is pretty easy to use, and comes from a library a lot of support.

Since the data source is configurable you can do things other than auto complete, such as synonyms.  It doesn't work on click though.  I don't know of anything that works on the click, since users normally would expect the caret to move on click, but if you really want it to work that way you could probably call the same code from the onclick event, more or less.


问:
Tutoring students who are struggling with the basics in C++
I am tutoring a few students who are having significant trouble learning the basics of their first programming language: C++. I have known many excellent and bright students who have failed or dropped their first CS course. Everyone I am tutoring gives a similar account of his or her experience in class: the instructor moves along too quickly, nothing in the lectures make any sense, et al. Prior to this CS class, most of these struggling students had not expressed any interest in computers as anything more than word processors, web browsers, or some other form of entertainment. The computer is a blackbox that works, so why mess with it?

My best guess is that they are having trouble connecting the abstractions of computer science with familiar concepts. That is to say, these student might know how to learn math, biology, or physics, but those techniques are not working when it come to programming.

Does anyone have any suggestions or advice?  The students I am helping do not deserve to fail this class. It is clear that the instructor is not taking into account the learning style of these students. That is to say, the instructor is failing not his students.

答:
When I was in college, I used to be a tutor for the intro to programming course among other courses. The problem you are describing is not uncommon. Depending on what your specific role is, you may have different approaches you want to take.

First, if this is a widespread problem affecting significant portions of the students in the class, if you have access to do so, I would approach the professor teaching the course with specific feedback about what concepts students are failing to grasp, so that he or she may either incorporate additional review of that material as it comes up again in the term, or improve the curriculum for future terms.

If you teach a discussion section for the course in addition to your lab time, that would be a wonderful time to expound on the things that were confusing in lecture and help make them more concrete and make sure fundamentals were all understood.

If the only time you work with these students is during your time in the tutoring lab, you can still use this time to teach the students either one on one, or a few at a time, the conceptual building blocks they need in order to understand and complete their homework.

They may feel so lost in class they don't even know where to stop and ask questions. If that is the case, go back to the basics with them. Where were they in the course when they last understood what was going on? If they are unsure, or "never" understood, you may have to go all the way back to the beginning to explaining hello world, teaching them things like what a variable is, how the computer takes their list of "instructions" and tries to do them in order, but the computer's not as "smart" as us so you have to be very literal and say things exactly right for the computer to understand, etc.

That's actually a point of struggle and frustration I've seen quite frequently in the non-majors programming courses. Students write some code. It seems "about" right, but then they go to compile it and it gives an error, a very cryptic error. And they have no idea what's wrong with it. And stare at their code for hours. Then finally figure out it was something that seems trivial, like a missing semi-colon, or a brace in the wrong place. Then they go compile it again, and there's still an error, it's something else. They spelled a variable name differently the second time they used it. And so on. So they ask a friend or tutor or someone for help, and they can answer off the top of their head "oh just add this there and then it will work." So their experience is that programming is a bit "mysterious" and extremely frustrating and way more trial and error than it should be.

That is an area as a tutor, where you have a lot of room to help. Depending on their frustration level, I might have different approaches to helping them figure out why their code isn't working. If they're sort of getting it, I might give them hints and try to help them figure out on their own. But if they're just at the end of their rope about ready to give up frustrated, I'll often give them a couple freebie answers, and then try to at least ask them questions like "do you understand why this change fixed your program?"

For some students, especially non-majors, they may not have the methodical attention to detail necessary to be a good programmer or enjoy programming. You can hand-hold them through strategies to help them pay attention to the details, and be methodical enough to solve the problems even if it is a challenge for them.

But anal-retentive about the students indenting their code "properly"--so often, beginning programmers create problems with nesting and scope because they have non-matching braces or the like because they don't pay attention to what's nested under what. Give them a checklist of "things to check when your program won't compile", like indent all the code properly and make sure the braces match, make sure all the lines end in semicolons, especially around the line number where the first error shows up, etc.

Teach them to compile early and compile often. Write the minimum skeleton code (say, hello world), compile/test. Add a few lines, compile again. Its much easier to find errors if you're only looking at a small bucket of changes not a big bucket.

Help them learn how to break down a problem into smaller solvable problems. This is the same thing we do as professional programmers solving much harder problems we don't know how to solve. You keep breaking it down into pieces until you get to something that you either know how to solve or can do some research to learn how to solve. "What steps would you need to take to get to a working solution?" Well, first you'd need some skeleton code (hello world). Do you know how to do that? Yes, great, so when we're done talking you can start by doing that! Then it needs to read a file as input. Did you remember reading about that in chapter 4? Not really? Why don't you go have a look at that after you get hello world running, and see how far close you can get to getting that working and then call me back and I'll help you some more when you get stuck on that. The first few times you may just need to make a numbered list for them of the steps necessary to solve the problem, so that they can learn from example how to decompose the problem.

If they are getting some but not all of the material in class, encourage them to ask questions in class, because nine times out of ten, they aren't the only student not understanding, and the professor probably did just gloss over something important.

If they are spending "hours" staring at one bug but not figuring it out, that's a waste of their time, they're not learning much from it. Often bugs are insight problems, and its a matter of coming up with the right insight to solve it, and they may not have a knack for those types of problems. Suggest other general approaches to take when they get stuck: ask another friend in the class for help (get to know some classmates if necessary to do so), start their homework way ahead of time so they have time to stop, and later come into the tutor lab and ask questions during the open hours, or go to the professor's office hours. If they're used to cramming, which works well for memorization subjects, they will hit a wall of frustration when they're faced with programming which is more about problem solving than memorization. Show them how to look up examples of syntax from their textbook, stackoverflow, etc. Encourage them to post a question on a private class question forum if there is one.

Teach them how to narrow down where the code stops working. Comment stuff out till you get back to something that runs, and then slowly add stuff back in until you get that segfault again.

A lot of these ideas could be turned into handouts if they come up a lot. Strategies is usually the part professors gloss over--they're spending their time on the syntax, the semantics of how to write loops, arrays, i/o, etc. But not enough time spent on "what do I do when I try to run my code and it just doesn't compile or crashes on me?"

When it comes to conceptual things, especially fundamentals, like "what is a variable", or "what is a loop?" not understanding that will prevent them from being able to keep up with the rest of the course. In a lecture-based course, the professor may not have time to answer every question or help that lightbulb go off for every single student. And that's part of why tutors are so important for learning programming. They may need individualized instruction with additional analogies to make a particular topic concrete.

Since you are teaching in C++, I would imagine classes come up as an abstract topic that some students struggle to "get". Often the abstraction of classes is taught with examples corresponding to some random real world object, like an "ATM machine", and analogies are made to the real world object. You might have variables to keep track of how much money is inside, you have methods, which are like rules that tell the atm machine how to respond to particular conditions, etc. Sometimes one analogy is the one that "sticks" for a particular person, and other students grasp a different one better.

Whenever possible, draw pictures for them. Like a sequence diagram of what happens over time to help them see the big picture of what the code they are writing does. User clicks this button. Then the program should respond by doing x, y, and z. Draw an array like a bunch of PO Boxes at the post office that can each hold only one number, and pointers like arrows pointing to the "address" on the front of the box. Etc.


答:
Here's some arbitrary rules for you to follow:

Don't write too smart or weird or unnecessary code

Long function names are not very good

ForceSpecifiedWindowPosition is too long

Don't do workarounds. Do real fixes.

Naming classes and functions is important activity. Use enough time for it.


问:
Database source control
Should database files(scripts etc.) be on source control?
If so, what is the best method to keep it and update it there?

Is there even a need for database files to be on source control since we can put it on a development server where everyone can use it and make changes to it if needed. But, then we can't get it back if someone messes it up.

What approach is best used for databases on source-control?

答:
For Java, our team uses Flyway, which we find really easy to use and powerful.

If you're working in Ruby, Rails has Migrations which are also a powerful way of dealing with this problem.

Liquibase has already been mentioned -- it's a good solution but I found it more cumbersome than alternatives like Flyway.

Also, RedGate software offers a product called SQL Source Control that is designed for SQL Server.  I haven't used it myself, but one of my coworkers says it's great.

Title: Database source control


问:
Making an attractive, yet still technical architecture diagram
Does anyone have any advice for making an "attractive" software architecture diagram? My manager told me to make my current architecture diagram (which was built just using Visio and basic icons) more "attractive" for a presentation I have to give to executive level types who are non-technical. I'm guessing he meant to have something that you'd show to customers or for marketing people to use.

Any specific icon sets or particular tips people have? I cannot post my current diagram for privacy reasons but to get the general idea, it's just text, lines, and server icons (http://www.227volts.com/wp-content/uploads/2009/03/exchange2007visiostencils.jpg) that is the icon set that I am using.

I'm honestly confused on how to make something like that "more attractive" (hell, I think black and white are always the best color combinations to use :P)

Edit:

So is something like this http://rollerweblogger.org/roller/resource/linkedin-today.png still considered "professional" with all the colors and such?

I asked my manager and all he said was just make it more marketable while evading questions about what I should do specifically.

答:
Be consistent in the font. Space things equally apart and keep them in alignment. Probably add a color or two (company colors?) beyond black and white. Headers in bold. Borders should be distinct. Something a little more than gridlines as the background or none at all.

You may have to break up into separate pages/slides. Nobody wants to see 57 blocks in some chaotic bird's nest diagram (by their perception).

You may want to consult someone in your company with a little more asthetic sense. Run it by someone in sales or marketing.


问:
How do I convince my fellow devs to WANT to add comments to source code commits?
I know that Subversion (what we're using at work) can be configured to require comments on commits, however I'm not in a position of power to simply turn this on.  I know that my reason for commenting my commits is because it is useful, if only as a memory-jogger, to quickly understand the reason behind the commit.  However, this doesn't seem to be enough to combat the two responses I always get:

It takes too long and I just want to get my changes into the repo.

It's easy enough to just look at the diffs.

I even show them the value of simply putting in a JIRA issue ID and how it automatically gets tied to the issue, but still no dice with them.

Worst of all, the person who can make the call is in the same camp: doesn't want to bother and is fine with looking at diffs.

I know it's the right thing to do, but how can I make them see the light?  Even if I can't convince my fellow devs, how can I convince management that it's the right thing to do for the business?

答:
Here's some advice:

Don't try to change the world. You will fail.

Instead you should regognize that everyone does work slightly different way. No one size fits everyone.

requiring some specific steps to people's work processes is very evil. Changing these processes takes 10 years. You're asking them to do this before next deadline.

Even simple process changes can take long time.

Some small comment on commits is way too insignificant to change these processes.

You can assume they do quality work, but should give enough freedom to choose the steps themselves. Some burdensome steps might not be needed for experienced developers.

If you're babysitting newbies, then stronger processes might be necessary, but experienced developers shouldn't deal with bullshit.

Imposing draconian restrictions on how work must be done is never ever going to work, it can only slow people down(might be good if they're too fast)

There are lots of people who think their way is the only right way to do things. Hope you're not one of them.


答:
It is probably needless to emphasize that the beauty is one of the most subjective opinions ever. As they say, the beauty is in the eye of the beholder, so what is beautiful to you may be ugly as hell to someone else. A lot of better halfs would concur.

That being said, nowadays people probably expect a little more than an ASCII diagram. You don't have to study the theory of colors, but shaping it up a little won't hurt. Sites for making diagrams like, for example, Gliffy have decent looking templates that I bet, would please anyone (or at least, not displease) attending that presentation.

Title: Making an attractive, yet still technical architecture diagram

Body:
Does anyone have any advice for making an "attractive" software architecture diagram? My manager told me to make my current architecture diagram (which was built just using Visio and basic icons) more "attractive" for a presentation I have to give to executive level types who are non-technical. I'm guessing he meant to have something that you'd show to customers or for marketing people to use.

Any specific icon sets or particular tips people have? I cannot post my current diagram for privacy reasons but to get the general idea, it's just text, lines, and server icons (http://www.227volts.com/wp-content/uploads/2009/03/exchange2007visiostencils.jpg) that is the icon set that I am using.

I'm honestly confused on how to make something like that "more attractive" (hell, I think black and white are always the best color combinations to use :P)

Edit:

So is something like this http://rollerweblogger.org/roller/resource/linkedin-today.png still considered "professional" with all the colors and such?

I asked my manager and all he said was just make it more marketable while evading questions about what I should do specifically.


答:
This question is too large to be answered exactly point by point. There are books about design, and other books about user experience, which explain in every detail how to make the software, consumer products, books, advertisements, toys for babies more attractive to the target audience. Actually, your question is similar to:

I'm a designer, I have some idea of programming (I learned Basic at school for two weeks) but I don't have time to learn programming. I am asked to do an e-commerce website from scratch using ASP.NET MVC and Microsoft SQL. Can you explain me what's those two things and how can I use them to do a successful work?

In all cases, if you want to make "attractive" charts but don't have time to read dozens of books and you don't have a designer in your company (is it possible?), you can try to inspire yourself from what you see around: professional websites, presentations, etc. You have to note some rules and patterns, and apply them to your charts. You may get it wrong sometimes, because some rules work well for websites but fail for consumer products or charts or toys for babies, but in general, you have more chances to succeed.

For example, if I take the chart in your edit:

I notice the very first error: shadows. Shadows must be used with caution. In a website, such usage would be unacceptable. A good example of how shadows must be used is Apple.com. Each element the user can interact with has a small shadow, giving a feeling of a volume. No other element has a shadow. In a case of a chart, this may be more acceptable, since users are not intended to interact with the chart. Still, shadows are too large and too separated from the elements. Also, here, there is no need for them: each element has already a border.

Rule of thumb: KISS (or, if you want, "be lazy"). Don't add a border and a shadow and a background color at the same time. Don't make the text bold italic Arial Black 200 red underlined with a yellow border on lime background blinking. Do only what you need to do to add visual impact, nothing more.

Think about styling your charts: nobody wants to see those ugly black and white UML diagrams. But don't overstyle: it will only become worse: UML black and white diagrams are ugly but usable. A rainbow multi-font blinking GIF-animated crap with plenty of icons and arrows that change color is not only ugly, but also unusable.

For the charts, remember the specificity of the context. If it will be shown through a projector, you can't have a green text on a white background: it will just magically disappear when projected on a wall. If it supports your talk, don't put too much on a slide: too much graphics, too much numbers, too much text. The illustration above is a good example of what you must never do for a presentation: with such slide, you're sure that half of the audience goes to sleep, and the other half stops listening to you, trying desperately to understand what's this thing.

Finally, remember that you're here for your audience, not the opposite. If you'll show the chart as the one illustrated above to marketing people, they'll say themselves that you suck. Do they know what is the cloud (or they believe it's something to do with applications which are hosted in the sky/space)? Do they know what represents the brown icon with "DB" on it? Can they explain what is a web app, and how is it different from something-else-app or from a website?


问:
Is there a general rule for when you should use 'make clean' instead of just 'make'?
I am writing a multiple-filed program right now, and apparently running only 'make' (as one would intuitively think needs to be done in most situations) for some reason causes my program to fail. I guess I can provide more detail of the problem, but the important thing is that it does run when using 'make clean'. So I was wondering if anyone knew the general rule of thumb for running 'make clean' instead of just 'make'</p>

答: I understand that this is your project, so it's your makefile.  My goal is to have make always produce a correct build, if it is possible to produce one.  If make clean is necessary to recover from some condition, then in my opinion the makefile is wrong, and should be corrected.  If your dependencies have been calculated correctly, then a simple make should recompile everything that needs to be recompiled.


答:
If your source control provdies it, turn on mandatory comments to prevent any un-commented commmits. Simple enough and everyone will soon realize that 5 seconds of typing a comment is painless.

But un-commented commits is one of the smallest negatives there is. I've been a part of many successful projects where not a single commit was commented. Don't get your panties in a bunch over it.

Title: How do I convince my fellow devs to WANT to add comments to source code commits?

Body:
I know that Subversion (what we're using at work) can be configured to require comments on commits, however I'm not in a position of power to simply turn this on.  I know that my reason for commenting my commits is because it is useful, if only as a memory-jogger, to quickly understand the reason behind the commit.  However, this doesn't seem to be enough to combat the two responses I always get:

It takes too long and I just want to get my changes into the repo.

It's easy enough to just look at the diffs.

I even show them the value of simply putting in a JIRA issue ID and how it automatically gets tied to the issue, but still no dice with them.

Worst of all, the person who can make the call is in the same camp: doesn't want to bother and is fine with looking at diffs.

I know it's the right thing to do, but how can I make them see the light?  Even if I can't convince my fellow devs, how can I convince management that it's the right thing to do for the business?


答: Use rounded corners and muted colors.  Use thick lines.  Elliance has some good examples. I'm not allowed to post images, though, but here is an example I've used as inspiration for my own diagrams.</p>


问:
Getting started with repositories: are they what I need, or are there any alternatives?
I'm a solo iOS developer - mostly self taught, but have made several successful apps so far and potentially starting some slightly bigger projects.

What I want to do:

As I'm working on some bigger and more complex apps now, there's some things that I want to do - which from what I gather, repositories are what I should be looking at. Basically, I want to:

Online backup of all my code (for now, dropBox works fine)

Work on new features of apps, while somehow being able to update/bugfix the older version and have the changes applied to both versions

So, are repositories what I should be looking into? From the brief look I've had, it does look like a bit of a learning curve, with the downside that I could only do work when an internet connection is available (sometimes not the case).

Is there:

any alternative to repositories that would achieve the 'branching'/new features - e.g. is there any way to already achieve this using Xcode and not relying on some server? This would be the easier option in my case.

Alternatively, if there isn't: What repository system would be best for me, and easiest to use (and probably free!)?

答:
Git is the answer to all of your problems--at least the ones you mentioned. There is a little bit of a learning curve to it, but it's free, and ridiculously powerful. Branching is easy (in fact, the recommended workflow is to make a branch for every single feature/bug/etc, and use throw-away branches for integration testing), off-site backup is trivial, and there are a handful of guis that help look at branching and history.

For off-site, there are free options if your source is open, you can pay for private repo hosting, or you can do it yourself by keeping a copy (even your working copy) in dropbox.

Here is a link to the install site: http://code.google.com/p/git-osx-installer/

Here are some articles to get you started:

http://www.vogella.de/articles/Git/article.html

http://sixrevisions.com/resources/git-tutorials-beginners/

https://stackoverflow.com/questions/216212/how-do-you-maintain-development-code-and-production-code#216228

https://github.com/bard/sameplace/wiki/Typical-Git-workflow

Update:
Xcode v4 has built-in git integration.


答:
It's called source control or revision control, and if you're working on code, having a system in place is incredibly useful and important.

First off, there are online source control providers, like unfuddle and github, which provide hosting for code and a lot of other convenience around them. However, they usually cost money if you want to keep your code private (though unfuddle and bitbucket do offer free, private repositories).

That said, git is one of the most popular source control tools out there now, and it's pretty easy to use once you learn the basics. It's also what github and unfuddle use. git doesn't need a central server, so you can have source control with you, even if you're offline. It provides branching, histories, diffing, etc. If you keep your code in a dropbox folder, that's fine too. It's easiest if you have the dropbox client installed on your computer, so that it syncs a folder to your computer.

If you have xcode 4 installed, it should have also installed git into your command line, and the IDE should be integrated with git.

Title: Getting started with repositories: are they what I need, or are there any alternatives?

Body:
I'm a solo iOS developer - mostly self taught, but have made several successful apps so far and potentially starting some slightly bigger projects.

What I want to do:

As I'm working on some bigger and more complex apps now, there's some things that I want to do - which from what I gather, repositories are what I should be looking at. Basically, I want to:

Online backup of all my code (for now, dropBox works fine)

Work on new features of apps, while somehow being able to update/bugfix the older version and have the changes applied to both versions

So, are repositories what I should be looking into? From the brief look I've had, it does look like a bit of a learning curve, with the downside that I could only do work when an internet connection is available (sometimes not the case).

Is there:

any alternative to repositories that would achieve the 'branching'/new features - e.g. is there any way to already achieve this using Xcode and not relying on some server? This would be the easier option in my case.

Alternatively, if there isn't: What repository system would be best for me, and easiest to use (and probably free!)?


问:
Is JSP a good alternative to PHP
I'm wondering is JSP a safe alternative to PHP? Some things I'm concerned about are cpu usage, memory usage, and security. </p>

答:
JSP is an alternative to PHP like any other programming language, and just like PHP is an alternative to anything other.

CPU-wise, it will depend on your applications. JSP, as ASP.NET, are compiled and run in a virtual machine; PHP, on the other hand, is interpreted. In both cases, the bottleneck would probably be the database access or your application itself, not the underlying language mechanisms.

As for memory usage, from what I've seen, small applications have a smaller memory footprint when written in PHP, and the opposite is true for large apps. Again, this is only my personal experience, and other people may not obtain the same results with their apps.

Finally, security-wise, it's up to you to make an application secure. If you know one language well, but not the other one, you surely will do some mistakes in this other language, making your applications unsafe.

If:

you have a precise design of an application to create, and:

you and your colleagues know equally well both languages, and:

there are no constraints server-side,

then you can do some assertions about:

the bottlenecks,

which language will help you to be more productive for a specific project,

which language to choose to ensure that your company will have enough specialists in a future to maintain the application.

For the bottlenecks, after making those assertions, you have to profile them to have a good image of the reality. Expectations about the performance are usually wrong.

In practice, the second and the third conditions enumerated above are hard to match:

There are chances that in your company, more developers are using PHP more often than JSP, or the opposite, or if they know both equally well, they prefer JSP,

There are even more chances that the server stack has a set of constraints, making it more difficult to implement one technology over another. For example if I have to do a web application which will use Microsoft SQL Server, chances are I will use ASP.NET over PHP, even if both can use Microsoft SQL Server.

Title: Is JSP a good alternative to PHP


问:
For what common problems is functional programming not a good fit?
Functional programming is a declarative paradigm. One of the strenghts with FP is that side-effects are avoided. It's said that for some problems FP isn't a good fit.

For what common problems isn't functional programming a good fit?

答:
Applications that are very stateful in nature. Video games are a good example because they model the real world. It makes much more sense to think about modifying the state of the world instead of rebuilding from the previous state every time something changes.

A concrete example would be changing the health of a monster after it gets shot. It's a lot more sensible to simply alter its health than to replace it with an entirely new monster that is the same in every way except now it has less health. These kind of changes make up just about everything in a game world, and doing this in a pure functional manner is not very intuitive. I imagine there may be some significant performance penalties, at least if you're doing it in a purely functional language.

(As a side note, some problems in games are very well suited to functional programming, such as AI. A hybrid functional/imperative language would be an excellent fit for those cases.)

ContentLicense: CC BY-SA 2.5


问:
Is it true that having the Nexus S is much better as an Android developer?
Soon, I'll be starting Android development, as I know a bit of Java. I'll also be getting an Android phone. My two options are the Nexus S and the Atrix 4G. I've heard the Nexus series is ideal for developers - can someone tell me why? Why is getting the Atrix bad as a developer?</p>

答:
The Nexus S could be considered "better" for two main reasons:

It features only standard Android software, nothing custom from the manufacturer or carrier, and

It gets updated faster than other handsets (because the updates come directly from Google, whereas other phones need to wait for the manufacturer to release the update and sometimes the carriers delay updates even further).

On the other hand, the Atrix has a faster processor (dual core, the Nexus S is only single core and basically just a slightly modified Galaxy S), better display and (IMO) looks better, too :-)


答:
if your development require you to support the latest released android OS version

fast updtes to the OS is the main reason you should consider nexus  phones

Title: Is it true that having the Nexus S is much better as an Android developer?

Body: Soon, I'll be starting Android development, as I know a bit of Java. I'll also be getting an Android phone. My two options are the Nexus S and the Atrix 4G. I've heard the Nexus series is ideal for developers - can someone tell me why? Why is getting the Atrix bad as a developer?</p>


问:
How do freelancer web developers manage web hosting for customers?
I have built a number of websites for friends, family, etc. and I have put them all on a single shared web hosting account. Now that they are built, I want to get out of business of supporting them and paying for them (my friends are reimbursing me but I am paying for the actual bill) so I was thinking of having them create their own hosting accounts and slowly migrating the sites over.

It got me thinking how does any freelancer do this? Do they force their clients to setup their own hosting up front and let the programmer log into the customer account during development. What if there is a bug in the future and they need to go back in?

I was curious to see what model most people use who build websites for others as it seems like a tricky situation.

答:
This is business, and to be honest with you, I've seen many models. For example, I know a guy who has hired a physical dedicated server (not virtual), and he hosts almost all of his projects on that (with low user statistics, of course) server. He usually gets even more money from his freelancing, doing support job. This way, he says that he gets kind'of job security, because he charges his customers for any kind of support task and he actually is paid good for that.

On the other hand of this model, you can see developers, who only develop the website/web application for their clients and simply deliver the code in return of the agreed-upon money. So, in this model, clients are all responsible for their networking issues, including network security, renewing their domain, etc.

To be honest, there is a golden rule in business:

The better way is the more economical way.

In business, people are after money. Some good businessmen tend to follow business ethics, but there are also people who don't care about that. So, I think you should choose your plan based on the most economical benefit it can bring you.


问:
Design Pattern For UI Control and Provider to Call Control's Events
I have a UI control that uses a provider class to implement the actual logic of a complex task.  So the control delegates to the provider to do some work.  But the provider needs to work with the control too; it needs to fire some events on the control.

I was looking for a good design pattern of how the two could work together, but wasn't sure of any.  I didn't want the  provider to directly invoke events on the control.  I thought about methods on the control that it could call, but I don't know that I quite like that either.

Any ideas, thoughts?  What is a good design pattern that the provider can use to fire a notification through the control?  Each event may also need to pass custom parameters too.

答:
I can think of two models:

Using callback functions

If your language supports passing functions as parameters, then you can call the provider's method from UI, passing it a function to be executed at the appropriate point. C# and JavaScript support this method. The code can be something like this:

```<code>provider.DoSomething(successCallback);
function successCallback () {
    // This function is written in UI and belongs to UI, but would be executed in provider.
}
</code>```

Using events

In this model, you can expose custom events in your provider to the external world. This way, you can provide event handlers for those events in your UI. For example, imagine that a provider tries to validate an order. This provider can expose an event called OrderValidated to the external world, and UI is just something existing in that external world. UI on the other hand can provide a handler for that event called HandleOrderValidated. In fact, UI subscribes to an interesting moment of the internal life-cycle of provider, and when that interesting moment comes to reality, provider informs any subscriber, and each subscriber takes its own action.

Body:
I can think of two models:

Using callback functions

If your language supports passing functions as parameters, then you can call the provider's method from UI, passing it a function to be executed at the appropriate point. C# and JavaScript support this method. The code can be something like this:

provider.DoSomething(successCallback);
function successCallback () {
    // This function is written in UI and belongs to UI, but would be executed in provider.
}

Using events

In this model, you can expose custom events in your provider to the external world. This way, you can provide event handlers for those events in your UI. For example, imagine that a provider tries to validate an order. This provider can expose an event called OrderValidated to the external world, and UI is just something existing in that external world. UI on the other hand can provide a handler for that event called HandleOrderValidated. In fact, UI subscribes to an interesting moment of the internal life-cycle of provider, and when that interesting moment comes to reality, provider informs any subscriber, and each subscriber takes its own action.


答:
What you are looking for is distributed source control. The two most popular solutions at the moment (which happen to be of excellent quality, and FOSS) are git (which is what the linux kernel project uses) and mercurial. In terms of features and usage, they are very similar, they are both excellent, so which one you use doesn't matter much. Git (written in C and shell script) performs a bit better on Unix-likes and has somewhat richer features (in areas you don't need to worry about right now, maybe never); mercurial (written in python) tends to be more non-Unix-friendly.

For both of them, there are free online hosting services; the most popular ones are gitbhub for git, and bitbucket for mercurial. Both offer unlimited free hosting for open source projects, but since they also need to make some money, they impose some limits on other services - with github, you need to pay for private repositories, bitbucket allows private repositories in the free account, but limits the total number of private committers to 5 (which, for a solo developer, is a non-issue).


问:
Open Source Friendly IP Contracts for Freelancers
I am about to enter the world of consulting for the first time and am having to write my first contract. One problem I have is regarding open source work and intellectual property. I love working on open source projects, whether it's an existing project or a project that I start on my own.

The question is: how can I write my contract to accommodate the following situations:

In the course of working on the client's project, I want to open source part of the code to the community under my own name.

In the course of working on the client's project, I am making use of some of my existing open source projects, and am making improvements to them.

In the course of working on the client's projects, I make improvements to third party open source projects and contribute them back.

In the course of working on the client's project, we decide to open source part of the code under the client's name.

What are the precedents to this if any?

Update: I added a item in the list above(item #3).

答:
The usual IANAL applies, which means, consult an actual lawyer.

That said, my take would be:

...is a tough one. It's unlikely that a customer is willing to pay you for software which you are going to open-source immediately. You can ask, and if they agree, set up a contract accordingly, but my guess is it's not going to happen.

...is also rather unlikely, but with a well-crafted contract that clearly defines the boundaries, and agreeing that you will not get paid for working on your own open-source projects (whether you are using the code or not) may be acceptable to customers. You may even be able to convice them to financially contribute to your project, but in any case, you need to put considerable effort into setting up a good contract.

...is at the client's discretion. Usually, a client will want the advantage they are paying you for, which means they don't see any benefit in open-sourcing their property, but there may be cases in which you might convince them to do so, adding a bit of delay to keep the advantage, or publishing under a dual-license model.


答:
assuming this is completely unavoidable:

of the options, i'd use preventWindowFromJumpingWhenKeyboardAppears; also detailing the issue in the method's documentation (what versions it is known to appear, how to repro, or a case #).

if you are introducing something awkward, it's best to make that obvious, to detail the motivation/issue, and to quarantine the workaround. otherwise, people read it and get confused (or omit its use if they have not spent a lot of time with your interfaces). then they may remove it in the future because they are not sure why it exists ("... but it tested fine on the latest OS."). for really bad cases, i'll use even more syntactic stigma because the method name you have chosen does not stand out when scanned.

if you can keep it entirely within private implementation, even better.

finally, preventWindowFromJumpingWhenKeyboardAppears makes it pretty obvious at the call site that there is a legitimate bug as well as the context it pertains to, rather than some haphazard implementation. forceSpecifiedWindowPosition makes little sense in comparison.


问:
Writing robust code vs. overengineering
How do you guys know that you are writing the most robust code possible without overengineering?

I find myself thinking too much about every possible path that my code can take, and it feels like a waste of time sometimes. I guess it depends on the kind of program you are writing, but I don't want to use too much of my time taking situations into account that will never happen.

答:
write for reuse.

write tests. trivial, nontrivial, some absurdly complex ones to see how it handles under such conditions. tests will also help you determine the form of the interface.

write the program to fail hard (e.g. assertion). my code has a ton of reuse and i test for a ton of cases - there's more error checking/handling than actual implementation (based on line count).

reuse.

immediately fix things that go wrong.

learn and build from experience.

errors will come up along the way, but they will (fortunately) be localized and they will (in most cases) show up very early in testing. the other benefit of reuse is that the client/caller can save most of the error checking/scaffolding using that which is brought by the implmentation.

your tests shall then define your program's capabilities and how robust they are - keep adding tests until you are satisfied with the success rates and inputs; improving, extending, and fortifying as needed.

Title: Writing robust code vs. overengineering


问:
Do companies care about university grades when hiring programmers?
Most of my fellow students that I've talked to claim that aiming for good grades is useless as the companies don't care about them when hiring programmers. To them, it's enough to have simply attended courses which may be important, and that's that.

Is this true? Are university grades useless when leaving campus, or do employers ask to see them for an interview?

答:
In order to graduate at my university we had to do a major project, including non-trivial programming, with a suitable report, meaning quite a bit of work had to be done in order to have the project approved.  That work was time limited, and you had to manage your own time in order to finish the project.

Hence, presenting a university grade not only show that you have had a bit of theory, but also that you have managed yourself to finish a non-trivial project with a deadline.  What the project was actually about is less important, than the fact that you finished it in an acceptable state on time.


问:
Call GPL software from non-GPL software
Can I (legally) use a program that is released under GPL from another program that I'm writing and not have to respect the GPL (for the program I'm writing)?

For example, I have a GUI that uses a program (which is under GPL), can I hide the code in the GUI and even sell it?

答:
No.

GPL code can only be used by other GPL code.

Citing the first line of wikipedia's GPL article:

The GPL is the first copyleft license for general use, which means
  that derived works can only be distributed under the same license
  terms.

Bsides of that, the GPL is several pages long and exists in several versions.

Warning, personal rant ahead!

I personally dislike the GPL license a lot because of it's very restrictive and virus-like nature. They call it "free" but it is actually quite the opposite, GPL code cannot be used by anything except other GPL code. Thus forcing other projects into GPL or being forced to rewrite whole libraries, whether your current project is open source or not. There were huge open-source projects, like freeBSD for instance which were forced to rewrite hundreds of thousands of lines of linux code because their license was incompatible, it was too "free" in the sense "do whatever you want", which is obviously not compatible with GPL.

If you want a truly "free" license in the sense "do whatever you want", I recommend BSD or MIT license ...actually, most of the other licenses are OK. It's only GPL which is really problematic because how restrictive it is and how it forces others into it. Lastly, it is overly complicated.

Ah, yeah, it's also a one-way ticket. GPL can use code/libraries licensed from most licenses, but these libraries/code cannot use GPL code in turn.

Title: Call GPL software from non-GPL software


答:
I've done it in different ways, based on the type of project, the skill level of the client, and their level of trust/ongoing relationship with me.

For example, I have two customers who are small businesses and are very non-technical. Since I was creating a web application for them, and they didn't really need their own domain name (internal use), then I just set them up as a subdomain on my server, and they pay me a set yearly hosting fee. This was a win-win situation, because asking them to setup a hosting account and deal with that would have been difficult and it gives me complete control over the environment so that I can make sure the web app stays available for them.

For another customer who needed his own domain (commercial web app), I just advised him as to what exactly his hosting plan needed to be, and he purchased it and gave me the login information. Since I do continual work for him, I basically act as an admin on his hosting account. But if we ever severed our relationship, he could just change his passwords and I'd be out.

For other clients who already have the knowledge and infrastructure and it's just a one-time project, I usually set up a subdomain on my server for them during development (makes it easier for me to control and make updates), and then send them the code for them to install on their own server when everything is ready.

Title: How do freelancer web developers manage web hosting for customers?

Body:
I have built a number of websites for friends, family, etc. and I have put them all on a single shared web hosting account. Now that they are built, I want to get out of business of supporting them and paying for them (my friends are reimbursing me but I am paying for the actual bill) so I was thinking of having them create their own hosting accounts and slowly migrating the sites over.

It got me thinking how does any freelancer do this? Do they force their clients to setup their own hosting up front and let the programmer log into the customer account during development. What if there is a bug in the future and they need to go back in?

I was curious to see what model most people use who build websites for others as it seems like a tricky situation.


答:
Depends what you mean by use it?

compile it into your code

use a shared library

run an executable

It also depends exactly which version/variant of the GPL the other code is under.

GPL

LGPL

AGPL

Probably others

Legal disclaimer: I am not a lawyer.

Title: Call GPL software from non-GPL software

Body:
Can I (legally) use a program that is released under GPL from another program that I'm writing and not have to respect the GPL (for the program I'm writing)?

For example, I have a GUI that uses a program (which is under GPL), can I hide the code in the GUI and even sell it?


答:
That depends on how exactly your program is "using" the GPL program. The GPL FAQ has a rather long explanation, but it still leaves a lot open to interpretation:

You cannot incorporate GPL-covered software in a proprietary system.
  (...) However, in many cases you can distribute the GPL-covered
  software alongside your proprietary system. To do this validly, you
  must make sure that the free and non-free programs communicate at arms
  length, that they are not combined in a way that would make them
  effectively a single program. (...)  if the two programs are combined so that they become effectively two parts of one program, then you can't treat them as two separate programs. So the GPL has to cover the whole thing. If the two programs remain well
  separated, like the compiler and the kernel, or like an editor and a
  shell, then you can treat them as two separate programs—but you have
  to do it properly. The issue is simply one of form: how you describe
  what you are doing. Why do we care about this? Because we want to make
  sure the users clearly understand the free status of the GPL-covered
  software in the collection.

I think in your example of a GUI that exists mainly to call a command line GPL program, the two clearly form a single program, so you'd have to release your code under the GPL.

Title: Call GPL software from non-GPL software


问:
Memory problems with singletons in a test suite
I am having a memory leak when running a test suite due to singleton objects are created and not cleared after each test case. And these singleton objects are holding references to heavy objects.

So I don't know if there is a better solution than clearing the singleton objects in the tearDown() methods in each test class!

What do you think?

答:
So I don't know if there is a better solution than clearing the
  singleton objects in the tearDown() methods in each test class!!

Get rid of the singletons. Singletons are hard to test anyway (global state). Use dependency injection instead. Mock heavy objects with lightweight ones if you're still in trouble.

If you really can't get rid of those singletons, then try to "clear" them after each test. The "clear" needn't necessarily be in the tearDown() method, although it's a good place for such tasks.


答:
typically, this means the singleton has outgrown its original intention, and should be made a standard object (read: not a singleton).

testability is one major reason. pains updating programs to use multiple instances are another. yet another: it's often a difficult bottleneck at execution. the singleton pattern is often overused, used for the wrong reasons, and leads to issues (like this).

so, you typically just make the object not function as a singleton anymore, or abstract its true shared exclusive data (if any) behind the interface of some class. this shared data and init/destroy sequence indicates that it is a singleton for the wrong reasons, or has grown to provide too much functionality.

as far as heavy objects: you can create initializers/constructors to support this use: ObjectWithMovie(movie)

if you absolutely need (often for historic reasons, unless your team continues to write singletons) a big blob of global mutable state (which is the current sum of your program's singletons and other global state), i prefer to make one class to hold these -- then the holder is the only singleton and responsible for initialization/destruction. then the complexity of your global shared state becomes more obvious (coincidentally, the reason many people don't like doing this).

anyways, the singleton is tough to test and from what i have seen, most uses have been made singletons for no good reason -- this is just becomes a pain when you need to test, reuse, extend, et cetera.

then you can happily execute all your tests (in parallel) without elaborate start up/tear down sequences.

good luck

Title: Memory problems with singletons in a test suite

Body:
I am having a memory leak when running a test suite due to singleton objects are created and not cleared after each test case. And these singleton objects are holding references to heavy objects.

So I don't know if there is a better solution than clearing the singleton objects in the tearDown() methods in each test class!

What do you think?


答: Remove the Singletons. Then your problem is solved.</p>


问:
Algorithm for detecting a knob-turning gesture?
What is the math to identify a gesture for the motion made by two fingers turning a knob (tracking two sets for xycoords)?

Is there a library/api anyone is familiar with that contains a good library of gestures for multitouch applications?

答:
The math with two fingers (assuming that some API always gives you the centers of both fingers) is rather simple, but you get more than just turning. You get scaling and translating motion as well. You star with P1(0) (x1(0), Y1(0)) and P2(0) (x2(0), Y2(0)). Then compute Pc = (P1 + P2) / 2. After that adjust all of the subsequent coordinates such that Pc (center) is at (0, 0) by subtracting Pc from every point. After that you should be able to calculate how each of the fingers rotated around the center - how much it scaled and how much it turned with each step. Note that the user may have slided both fingers as well. Think watching a moving hurricane on a radar screen: it turns, it moves, it disperses and gets wider, or it gets smaller. If that sliding motion is significant, then you might want to compute the center dynamically.

Now, with N measurements of pairs of points P1 and P2, you should have data on how the center slided, how it turned, and how the radius changed. You are looking for little sliding, little radius expansion, and a linear increase/decrease of the angle with time. I would filter out big noise and then try to see how you can fit a straight line in your angle graph, and how well a line approximates it. Well ... the user can change the speed of rotation. Something that no generic library can do for you is decide on the rules for when to ignore a gesture. You need to provide more info on what the turning of the knob is like. I hope there are only 2 fingers involved. Are you trying to measure this turning or merely detect the motion?

EDIT: Thinking of the hurricane a bit more, I think it makes sense to compute the new center with every step. However, if one finger does not move, but the other does trace a circle, then it is a different type of motion than turning the knob. If you still model it as a knob, it will be interpreted as displacement with slow rotation as opposed to faster rotation around a static point.

Again, the math is not necessarily complicated. It is just a 2d transformation matrix + offset vector. But, when more than one finger is involved, the question becomes: what it the 'center' about which the transformation is being performed? It could be either 4 corners of the screen, the center of finger 1, the center of finger 2, the half-way point between two fingers, or other. How you interpret the motion will depend on the choice of the center. It might not matter too much if the users can easily learn and adjust their motion to get it working right. But you still want to take the best guess at how exactly they are planning on using the software, and what other gestures are there.


问:
Theta notation on constant time. Why we use the 1?
In asymptotic notation when it is stated that if the problem size is small enough (e.g. n<c for some constant c) the solution takes constant time and is writen as Theta(1).

Why we write 1  inside the Theta?

What does the 1 mean? Why not Theta(c)?

答:
Those notations are meant to denote the asymptotic growth. Constants do not grow and thus it's pretty equal which constant you choose. However, there's a convention that you choose 1 to indicate no growth.

I assume that this is due to the fact that you want to simplify the mathematical terms in question. When you've got a constant factor just divide by it and all that's left of it is 1. This makes comparisons easier.

Example:

O(34 * n^2) = O(1 * n^2) = O(n^2)

and

O(2567.2343 * n^2 / 5) = O(n^2)

See what I mean? As these mathematical terms get more and more complicated, you don't want to have noisy constants when they're not relevant for the information you're interested in. Why should I write O(2342.4534675767) when it can be easier expressed with O(1), which communicates the facts of the case unambiguously.

Further, the wikipedia article about time complexity also implies it's a convention:

An algorithm is said to be constant time (also written as O(1) time)
  ...


问:
Are design patterns generally a force for good or bad?
I've heard it argued that design patterns are the best thing since sliced bread.  I've also heard it argued that design patterns tend to exacerbate "Second System Syndrome," that they are massively overused, and that they make their users think they're better designers than they really are.

I tend to fall closer to the former camp, but recently I've been seeing designs where nearly every single interaction is replaced with an observer relationship, and everything's a singleton.

So, considering the benefits and problems, are design patterns generally good or bad, and why?

答:
It's often said that design patterns provide a ready-made solution for programming problems. What kind of problems are they? "How can I change object behavior, but isolate the changes from the rest of the system?"

The GoF patterns are recognized for providing that isolation (encapsulation) from the rest of the system, but it's often difficult to know what part of the system is given variability through the use of their design patterns. Instead of following the classification scheme they proposed (creational, behavioral and structural), I charted the patterns' differences and came up with two other schemes to classify their patterns: lifecycle and component encapsulation hierarchy.

As you can see from this table for the encapsulation hierarchy, design patterns can be applied at every level of a component. But would it make sense? Will the component need to provide behavioral variation at the encapsulation level proposed, and is the proper pattern used for that level? If these questions aren't properly answered then design patterns are most likely misapplied. Just because a vertical pivot could be built into the cabin of a car doesn't make it a smart idea.


答:
Well, of course you could write Theta(c) (or O(c)) but why does that differ from Theta(n)? n is just a variable that denotes the size of the input. You could write "The function is Theta(c) where c is a constant". The important addendum is ...where c is a constant. You have to explicitly state that an identifier is not a variable.

Consider graph theory where the bounds for an algorithm is often described as a function of |V| and |E|, or the node and edge count, respectively. Then it might be prudent to state "The function is Theta(|V| * |E|^2)".

Theta(1) however is always a constant - assuming normal mathematical practices.

Title: Theta notation on constant time. Why we use the 1?

Body:
In asymptotic notation when it is stated that if the problem size is small enough (e.g. n<c for some constant c) the solution takes constant time and is writen as Theta(1).

Why we write 1  inside the Theta?

What does the 1 mean? Why not Theta(c)?


答:
You can use a GPLed program from your own program without your program being affected by the GPL, but you cannot link the GPLed code into your own program without your program becoming subject to the GPL's terms.

In the example provided in the question, in which you have written a GUI wrapper around an existing command-line program, your GUI is not bound by the terms of the GPL, provided that it is a separate program which runs the GPLed program in a separate process and communicates with it only via the existing interface(s) - e.g., over the command line and/or via stdin/stdout.

Some relevant bits from GPL FAQ:

Where's the line between two separate programs, and one program with
  two parts? This is a legal question, which ultimately judges will
  decide. We believe that a proper criterion depends both on the
  mechanism of communication (exec, pipes, rpc, function calls within a
  shared address space, etc.) and the semantics of the communication
  (what kinds of information are interchanged).

If the modules are included in the same executable file, they are
  definitely combined in one program. If modules are designed to run
  linked together in a shared address space, that almost surely means
  combining them into one program.

By contrast, pipes, sockets and command-line arguments are
  communication mechanisms normally used between two separate programs.
  So when they are used for communication, the modules normally are
  separate programs. But if the semantics of the communication are
  intimate enough, exchanging complex internal data structures, that too
  could be a basis to consider the two parts as combined into a larger
  program.

Can I release a non-free program that's designed to load a GPL-covered plug-in?

It depends on how the program invokes its plug-ins. For
  instance, if the program uses only simple fork and exec to invoke and
  communicate with plug-ins, then the plug-ins are separate programs, so
  the license of the plug-in makes no requirements about the main
  program.

If the program dynamically links plug-ins, and they make
  function calls to each other and share data structures, we believe
  they form a single program, which must be treated as an extension of
  both the main program and the plug-ins. In order to use the
  GPL-covered plug-ins, the main program must be released under the GPL
  or a GPL-compatible free software license, and that the terms of the
  GPL must be followed when the main program is distributed for use with
  these plug-ins.

If the program dynamically links plug-ins, but the
  communication between them is limited to invoking the ‘main’ function
  of the plug-in with some options and waiting for it to return, that is
  a borderline case.

Note that the GPL applies in full to the underlying command-line program in any case - if you distribute it (as opposed to having users obtain it from another source), you are responsible for providing a copy of the GPL to users, making it clear to them that the command-line program is under the GPL (even if the GUI wrapper isn't), and making the command-line program's source code available to them on request.  From the GPL FAQ again:

If people were to distribute GPL-covered software calling it “part of”
  a system that users know is partly proprietary, users might be
  uncertain of their rights regarding the GPL-covered software. But if
  they know that what they have received is a free program plus another
  program, side by side, their rights will be clear.

Standard disclaimer:  I am not a lawyer and, even if I were a lawyer, I'm not your lawyer.  If you need a definitive answer, consult an appropriate legal professional who is licensed to practice in your jurisdiction.

Title: Call GPL software from non-GPL software


问:
How would you go about looking for collaborators?
I seem to have a never ending stream of more-or-less original, more-or-less cool ideas for software/apps/stuff yet to be written on my mind. Sometimes, I decide to just start implementing my idea. Several hours later, I end up with a decent, more-or-less working prototype of what I'm trying to build. Then, my alarm clock goes ringing and I have to get back to the real world, tired as hell. In most cases, the stuff I started remains unfinished forever. Sometimes, that's okay. Other times, I honestly feel like that's a bummer.

But I realize that there are sites like GitHub and there are many other coders out there. Is there a place where one can post ideas, proposals, concepts, or rough-around-the-edges-code in order to find people who are interested in collaborating on projects?

Edit: I am aware of "the usual way" – keep developing on your own for some period of time, open-source the code, mention your project on dev blogs, IRC or wherever else you go; eventually attracts others.

What I'm looking for is a place to connect with other devs (e.g. of different specializations) on the early stages of a project.

答:
I fonder if someone will partner on basis of just a proto-type. Even if someone likes the idea, he will go for the implementation on his own. You can only think of collaboration in terms of opensource project once you have a working model. People then can try your app and if interested collaborate with you.

That's just my way of thinking. Other answerer's may tell you the way to go for it.


问:
Making an attractive, yet still technical architecture diagram
Does anyone have any advice for making an "attractive" software architecture diagram? My manager told me to make my current architecture diagram (which was built just using Visio and basic icons) more "attractive" for a presentation I have to give to executive level types who are non-technical. I'm guessing he meant to have something that you'd show to customers or for marketing people to use.

Any specific icon sets or particular tips people have? I cannot post my current diagram for privacy reasons but to get the general idea, it's just text, lines, and server icons (http://www.227volts.com/wp-content/uploads/2009/03/exchange2007visiostencils.jpg) that is the icon set that I am using.

I'm honestly confused on how to make something like that "more attractive" (hell, I think black and white are always the best color combinations to use :P)

Edit:

So is something like this http://rollerweblogger.org/roller/resource/linkedin-today.png still considered "professional" with all the colors and such?

I asked my manager and all he said was just make it more marketable while evading questions about what I should do specifically.

答: Once you've done your diagrams using whatever development tools you normally use, re-do them from scratch in Powerpoint or whatever presentation software your company uses.  My presentations using the default icons and arrow styles have gotten much better response than those I've done in Enterprise Architect or Power Designer.  Skip UML and just go for simple relationship diagrams and flow charts.  As with any presentation, throw something together quickly and run it past your manager for feedback.  You don't want to be wasting hours laying out an elaborate workflow diagram that your manager will knock down for being "too busy".  I'd recommend doing one simple diagram completely, so you can show the style (font, color palette, layout), and mocking up the rest of it for content.  Then take it to your manager and get some further direction.</p>


答:
This is all very hand-wavy, but there is a mathematical reason why we don't use Theta(c) and instead use Theta(1). I'll use Big O notation instead to show this.

It has to do with a property of Big Theta (as well as Big O and Big Omega) notation. If you have a function with growth rate O(g(x)) and another with growth rate O(c * g(x)) where c is some constant, you would say they have the same growth rate. That is O(c * g(x)) = O(g(x))

We can say this because the definition of Big O notation (f(x) = O(g(x))) means that we have a function f(x) and function g(x) such that |f(x)| <= k * |g(x)| for some constant k and large enough values of x. When multiplying by the constant c, we would then have:

O(c * g(x)) => k * |c * g(x)| = k * |c| * |g(x)| <= k' * g(x)  where k' = k * |c|

Note that |k' * g(x)| <= k'' g(x) for some constant k'' and large enough values of x, which means k' * g(x) grows at a rate of O(g(x)) and therefore O(c * g(x)) = O(g(x))

When g(x) = 1, we have O(1) growth, saying O(c) growth for some value of c doesn't tell us anything because the constant is already factored in to the definition of Big O notation. Simplified O(c) = O(1)


问:
How do you measure the value of your software?
One of the principles of agile is that you should measure working software:

Working software is the primary measure of progress - 12 principles of Agile

The thing is, while I can measure my software in terms of stories done, bugs squashed or the volume of defect reports decreasing, I'm stuck on how to measure the value of my software.

If I use Mike Cohn as an example and his helping SalesForce.com deliver 500% more value to it's customers compared to the previous year* - how do I measure that increase? How do I measure where I am right now?

Other metrics he uses are the number of features and the number of features per developer. This is something I could work out if my backlog was in good order and the stories were cut up by 'feature', but we're just starting out with Agile, so I need some way of working out what the value is we deliver now, then use a similar metric in say, six months, to see if we've increased our output.

I've heard about measuring value of software by an uptick in revenue, or an increase in customer satisfaction (how would you measure that though?) but those increases could be attributed to anything in the company (sales, accounting, support) and not directly to the work my department is doing.

So, how do you guys measure the value of your software and how did you start?

* Succeeding With Agile - Mike Cohn

答:
Working software is the measure.  Listen openly to your users and involve them in the development process.  Regularly deliver the functionality that they tell you is needed when they need it.  Deliver in small chunks so users feel progress.

If you are just starting agile development or even a new project...then stakeholders need to have a bit of faith.  This requires the product owner to articulate why agile is better than other processes (I assume that you think it is in your specific situation).

If the product owner is not sure which features (stories) offer the most relative value then you need to sit down with stakeholders and figure it out.  Planning poker is a good tool for that.  Assigning Relative Business Value to each story also helps with prioritization but be careful not to talk to bean counters about "Agile Business Value" it's not the same as ROI!


答: Theta notation is about growth as a function of some variable - typically n. If it were necessary to clarify which variable is intended, the way to write it would be Theta(n^0). From there it's a simple step to apply the identity n^0 = 1 (for n != 0).</p>


问:
Is it worth it for a developer to be a scrum master? Is it an official designation or?
Is it beneficial for a developer to become a 'scrum master'?

Is this an official certification or just someone who specializes?

What are the steps towards becoming one?

答:
It is beneficial for a developer on an agile team to understand the scrum master role.  A cohesive agile team is built on trust. If, as a developer, you understand that the scrum master is a mentor, a facilitator and a protector of the team, you will be more likely to engage them in meaningful ways.

A developer talented in seeing the big picture, finding nuggets of gold in a mountain of dirt,   and who enjoys mentoring will be a great scrum master candidate.  It's my experience that the best scrum masters are naturally talented in these areas. Training will not make you a scrum master but may help hone your skills.


问:
Is return-type-(only)-polymorphism in Haskell a good thing?
One thing that I've never quite come to terms with in Haskell is how you can have polymorphic constants and functions whose return type cannot be determined by their input type, like

```<code>class Foo a where
    foo::Int -> a
</code>```

Some of the reasons that I do not like this:

Referential transparency:

"In Haskell, given the same input, a function will always return the same output", but is that really true? read "3" return 3 when used in an Int context, but throws an error when used in a, say, (Int,Int) context. Yes, you can argue that read is also taking a type parameter, but the implicitness of the type parameter makes it lose some of its beauty in my opinion.

Monomorphism restriction:

One of the most annoying things about Haskell. Correct me if I'm wrong, but the whole reason for the MR is that computation that looks shared might not be because the type parameter is implicit.

Type defaulting:

Again one of the most annoying things about Haskell. Happens e.g. if you pass the result of functions polymorphic in their output to functions polymorphic in their input. Again, correct me if I'm wrong, but this would not be necessary without functions whose return type cannot be determined by their input type (and polymorphic constants).

So my question is (running the risk of being stamped as a "discussion quesion"): Would it be possible to create a Haskell-like language where the type checker disallows these kinds of definitions? If so, what would be the benefits/disadvantages of that restriction?

I can see some immediate problems:

If, say, 2 only had the type Integer, 2/3 wouldn't type check anymore with the current definition of /. But in this case, I think type classes with functional dependencies could come to the rescue (yes, I know that this is an extension). Furthermore, I think it is a lot more intuitive to have functions that can take different input types, than to have functions that are restricted in their input types, but we just pass polymorphic values to them.

The typing of values like [] and Nothing seems to me like a tougher nut to crack. I haven't thought of a good way to handle them.

答:
Just to note a misconception:

"In Haskell, given the same input, a function will always return the
  same output", but is that really true? read "3" return 3 when used in
  an Int context, but throws an error when used in a, say, (Int,Int)
  context.

Just because my wife drives a Subaru and I drive a Subaru does not mean we drive the same car. Just because there are 2 functions named read does not mean it's the same function. Indeed read :: String -> Int is defined in the Read instance of Int, where read :: String (Int, Int) is defined in the Read instance of (Int, Int). Hence, they are completely different functions.

This phenomenon is common in programming languages and is usually called overloading.

OwnerDisplayName: dainichi


问:
Raw Sql vs SqlAlchemy when Django ORM is not enough
In a django project, if a situation comes that Django ORM is not able to execute some complex queries then there are 2 options:

Use Raw Sql queries

Use SqlAlchemy

I want to know if there are some rules like some pros and cons of both which can guide me to choose one of the above 2 options.
Or is it entirely depends on what we like?

答:
ORM

Pro Usable on different DBMS without code customization.

Pro Makes code/DB integration easier.

Pro Additional type checking from ORM/table definitions.

Pro Facilitate db migrations.

Pro Essentially a DSL for DB integration.

Con Additional component to understand (you should understand how the ORM will create the SQL)

Con Any SQL customizations eliminate the usability on different DBMS.

Raw SQL

Pro You know the SQL being used because it's there in the code.

Pro More control over the SQL and integration.

Pro Less complexity (no ORM).

Con Tied to one DBMS flavor of SQL.

Con Manual code/DB integration.

The issue of complexity

I'm sure I'll get dinged for this, BUT.

Unlike many of the its proponents I do NOT think ORMs free the developers from understanding SQL.  You still have to understand SQL because you will end up dealing with the SQL your ORM creates.  And here is why:

SQL statements are typically one of the first things that needs performance tuning in a given project.

ORMs are still young.  None that I know of implement an actual SQL parser which means, outside of trivial statements, the SQL constructed is often inefficient, and in some cases just wrong.

This doesn't mean you shouldn't use an ORM.  They can still reduce the amount of code you have to write.  But you should understand you may not get all the benefits you think you will.


问:
Should we quit trying to do agile if QA takes 12 weeks?
Someone in my company recently proposed changes to our core product that our managers feel should trigger what I guess my company considers a full QA cycle (i.e. testing the entire product suite from the ground up). Apparently our QA takes 12 weeks to do a full QA cycle for our product. My problem with this is that we are trying to do Agile (although mostly half-assed in my opinion) development. We will do a whole set of sprints and then do a release, which QA will take forever to go through I guess. The question is really, if our QA is going to take 12 weeks to do their job, shouldn't we just give up trying to do Agile? What the hell is the point of trying to do Agile in a situation like this?</p>

答:
The process you described is not an agile process.  Teams who have a high degree of agility are able to deliver reliable and potentially releasable builds every sprint.  In most agile implementations, the QA function is built within the agile team helping to achieve this goal.

If you, your project lead, your product owner and the developers are not working together and you do not have an improvement plan (retrospectives) then name your process something else and move on.  It does not appear that your teams problems are the fault of managers or QA.  They seem to be reacting to some systemic problem coming out of the development organization.  All is not lost if the team is willing to take responsibility and begin working with stakeholders.

You could try three things.  One, make sure each stakeholder has concisely defined roles and that each person understands their responsibility.  Two, stabilize the build and then get signoff from QA without introducing more changes.  Three, institute test automation.  The QA team will love you for it.