问:
Data classes: getters and setters or different method design
I've been trying to design an interface for a data class I'm writing. This class stores styles for characters, for example whether the character is bold, italic or underlined. But also the font-size and the font-family. So it has different types of member variables. The easiest way to implement this would be to add getters and setters for every member variable, but this just feels wrong to me. It feels way more logical (and more OOP) to call style.format(BOLD, true) instead of style.setBold(true). So to use logical methods instead of getters/setters.

But I am facing two problems while implementing these methods: I would need a big switch statement with all member variables, since you can't access a variable by the contents of a string in C++. Moreover, you can't overload by return type, which means you can't write one getter like style.getFormatting(BOLD) (I know there are some tricks to do this, but these don't allow for parameters, which I would obviously need).

However, if I would implement getters and setters, there are also issues. I would have to duplicate quite some code because styles can also have a parent styles, which means the getters have to look not only at the member variables of this style, but also at the variables of the parent styles.

Because I wasn't able to figure out how to do this, I decided to ask a question a couple of weeks ago. See Object Oriented Programming: getters/setters or logical names. But in that question I didn't stress it would be just a data object and that I'm not making a text rendering engine, which was the reason one of the people that answered suggested I ask another question while making that clear (because his solution, the decorator pattern, isn't suitable for my problem). So please note that I'm not creating my own text rendering engine, I just use these classes to store data.

Because I still haven't been able to find a solution to this problem I'd like to ask this question again: how would you design a styles class like this? And why would you do that?

答:
I smell an attribution list. I agree you should set format and get format, except I would use a list. A bit mask even if your attributes allow. Otherwise just keep an array of formatter objects which use IOC to format there field if possible.
forgive me, I don't know c++</p>

```<code>Public abstract class IFormatter
{
.   public abstract void FormatText(TextField* fieldToFormat);
}

Public class BoldFormatter : IFormatter
{...}

Public class TextField
{
.   public void AddFormatter(IFormatter* formatterToAdd)
.   {...}

.   public IFormatter[] GetFormatters()
.   {...}

.   public void Render()
.   {
.       foreach(IFormatter formatter in formatters)
.       { formatter.FormatText(this); }
}
</code>```

Body:
I smell an attribution list. I agree you should set format and get format, except I would use a list. A bit mask even if your attributes allow. Otherwise just keep an array of formatter objects which use IOC to format there field if possible.
forgive me, I don't know c++

Public abstract class IFormatter
{
.   public abstract void FormatText(TextField* fieldToFormat);
}

Public class BoldFormatter : IFormatter
{...}

Public class TextField
{
.   public void AddFormatter(IFormatter* formatterToAdd)
.   {...}

.   public IFormatter[] GetFormatters()
.   {...}

.   public void Render()
.   {
.       foreach(IFormatter formatter in formatters)
.       { formatter.FormatText(this); }
}


问:
How to learn to make better estimates?
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).

答:
Software Estimation by Steve McConnell (MS Press) is a good read.

The main thing with software estimate is summarized by the following

Without historical information, your
  estimates are useless.

This is one reason I think why iterative projects have much more success that large phased waterfall projects. They aren't trying to build out a plan for a year at a time with little information other than some black box voodoo of what they think it should be. Every iteration, they are reestimating/replanning and have the last several iterations to base their estimates on.

A few other points to keep in mind:

It will only get slower. Applying the 80/20 rule means that the harder work will come later unless your project management is very disciplined.

Estimation != Planning. Estimation is the process of figuring out the effort required to get something done. Planning is the process of fitting it into a schedule.

60% efficiency is about all you can hope for. 70% is utopia. If you're estimating in days, build this in. If you're estimating in hours, don't forget to apply it later.

Remember the long tail. Estimates are a rough guess of how long it "probably" will take adjusted for some level of risk and unknowns. The long tail comes into play because the actual amount of work required will never be less than 0. OTOH, the maximum amount of time it will take is only limited by how long you're willing to spend on it before giving up. As  a former boss of mine said "all estimates are +/- x% and it's never minus".

ContentLicense: CC BY-SA 2.5

Title: How to learn to make better estimates?


答: If all they do is store data, then why bother with any kind of getter and setter? You have no invariants to enforce, no logical reason to control the data, and no reason to process it nor prevent access. The class's reason to be is "Store data". So make it store some data and leave it at that.</p>

ContentLicense: CC BY-SA 3.0

Title: Data classes: getters and setters or different method design

Body:
I've been trying to design an interface for a data class I'm writing. This class stores styles for characters, for example whether the character is bold, italic or underlined. But also the font-size and the font-family. So it has different types of member variables. The easiest way to implement this would be to add getters and setters for every member variable, but this just feels wrong to me. It feels way more logical (and more OOP) to call style.format(BOLD, true) instead of style.setBold(true). So to use logical methods instead of getters/setters.

But I am facing two problems while implementing these methods: I would need a big switch statement with all member variables, since you can't access a variable by the contents of a string in C++. Moreover, you can't overload by return type, which means you can't write one getter like style.getFormatting(BOLD) (I know there are some tricks to do this, but these don't allow for parameters, which I would obviously need).

However, if I would implement getters and setters, there are also issues. I would have to duplicate quite some code because styles can also have a parent styles, which means the getters have to look not only at the member variables of this style, but also at the variables of the parent styles.

Because I wasn't able to figure out how to do this, I decided to ask a question a couple of weeks ago. See Object Oriented Programming: getters/setters or logical names. But in that question I didn't stress it would be just a data object and that I'm not making a text rendering engine, which was the reason one of the people that answered suggested I ask another question while making that clear (because his solution, the decorator pattern, isn't suitable for my problem). So please note that I'm not creating my own text rendering engine, I just use these classes to store data.

Because I still haven't been able to find a solution to this problem I'd like to ask this question again: how would you design a styles class like this? And why would you do that?


问:
MVVM - child windows and data contexts
Should a child window have it's own data context (View-Model) or use the data context of the parent?  More broadly, should each View have its own View-Model?  Are there are any rules to guide making that decision?  What if the various View-Models will be accessing the same Model?

I haven't been able to find any consistent guidance on my question.  The MS definition of MVVM appears to be silent on child windows.

For one example, I have created a warning message notification View.  It really didn't need a data context since it was passed the message to display.  But if I needed to fancy it up a bit, I would have tapped the parent's data context.

I have run into another scenario that needs a child window and is more complicated than the notification box.  The parent's View-Model is already getting cluttered, so I had planned on generating a dedicated VM for the child window.  But I can't find any guidance on whether this is a good idea or what the potential consequences may be.

FWIW, I happen to be working in Silverlight, but I don't know that this question is strictly a Silverlight issue.

答:
I guess it depends.  On the project I am currently working on, we have used both approaches.  I suppose it comes down to how related the child window's functionality is to the parent.  If the new window is mostly supplemental, such as a prompt or minor input dialog, I have simply used the parent's data context because the data being provided through that dialog was still very relevant to the parent's functionality.  On the other hand, if the new window is a significant feature in itself, it may be more appropriate to use a new data context that reports back to the parent (if applicable).  Think of it this way, when designing a class, when is it appropriate to break out functionality into another class? You don't necessarily want an unwieldy view-model with a bunch of unrelated functionality lumped together.

Unfortunately, this has turned into a pretty fuzzy answer that depends on your best judgment.

Title: MVVM - child windows and data contexts


问:
*Code owner* system: is it an efficient way?
There is a new developer in our team. An agile methodology is in use at our company. But the developer has another experience: he considers that particular parts of the code must be assigned to particular developers. So if one developer had created a program procedure or module it would be considered normal that all changes of the procedure/module would be made by him only.

On the plus side, supposedly with the proposed approach we save common development time, because each developer knows his part of the code well and makes fixes fast. The downside is that developers don't know the system entirely.

Do you think the approach will work well for a medium size system (development of a social network site)?

答:
The disadvantage is severe; the "truck number" of your team pretty much becomes 1.

To review, the "truck number" is defined simply as "how many members of the team, worst-case, could be hit by a truck before knowledge necessary to perform some critical task is lost to the team."

It is natural, and somewhat to be encouraged, for developers to focus on sub-disciplines; if everybody had to know everything having to do with the project, nothing would get done because everyone would be learning what everyone else had done, why it works and how it can be changed without breaking it. In addition, if devs are off doing different things to different areas it's less likely that changes will collide. So it's generally good to have two or three developers or dev pairs that work primarily in a particular subsystem of the project and know it well.

However, if only one person is ever supposed to touch a particular line of code, then when that guy quits, gets fired, goes on vacation, or ends up in the hospital, and that line of code is demonstrated as the cause of a bug that must be fixed, someone else has to go in and understand the code. If nobody else but the guy who wrote it has ever seen it, that will take time in order to get to a level of understanding that allows the developer to make the change that fixes the bug without making more. TDD can help, but only by telling the developer they made the "wrong" change; again, the developer must understand what tests are exercising which code in order to make sure that failing tests aren't trying to make the wrong assertions.


答:
I don't take it to the extreme, but I prefer code responsibility. You write broken code, you should fix it. This can be done at the individual, pair, or team level. It prevents passing your mess off to someone else to clean up. This goes for changes as well.

Workload and scheduling issues will overwrite this. It would be foolish to hold off fixing a major bug because the culprit is on a two week vacation.

The goal isn't to have your team play "the blame game" or take bug counts too far (They're not all equal anyway.). Base it on who checked the code in last or have a supervisor make the decision and assign it to someone instead of going through every part of every line of code.

Better programmers probably end up fixing a lot of other people's code no matter how you assign it.

Title: *Code owner* system: is it an efficient way?

Body:
There is a new developer in our team. An agile methodology is in use at our company. But the developer has another experience: he considers that particular parts of the code must be assigned to particular developers. So if one developer had created a program procedure or module it would be considered normal that all changes of the procedure/module would be made by him only.

On the plus side, supposedly with the proposed approach we save common development time, because each developer knows his part of the code well and makes fixes fast. The downside is that developers don't know the system entirely.

Do you think the approach will work well for a medium size system (development of a social network site)?


问:
"Do you have any questions for us?" In an interview
You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>

答:
I like to ask one or two fairly casual questions about current "stuff" in the company.  This might be a question about their newest product.  Or it might be a question about an emerging market I know they're exploring.  Or I might ask if they have a major release of product X coming up.

(I mostly learned this from interviewees asking these types of questions to me.)

I think one reason this works well is because people love to talk about what they're currently working on, or what's new and interesting in their company.  It gives them a chance to feel knowledgeable and end the interview on a high note.

Another reason I think it works well is it shows interest on your part in what the company's up to.  And, depending on what all went on in the interview, it may give a sense that you did some research into the company beforehand (you did, didn't you?), and have a sort of unique interest in what the company does.

Perhaps more than the above, I think it's good to not drop any "heavy" questions at this stage.  My best interviews (giving and taking) have always wrapped up on a relatively light, conversational, friendly note.


问:
Good practices for large scale development/delivery of software
What practices do you apply when working with large teams on multiple versions of a software or multiple competing projects? What are best practices that can be used to still get the right things done first?

Is there information available how big IT companies do development and management of some of their large projects, e.g. things like Oracle Database, WebSphere Application Server, Microsoft Windows, ....?

答:
You're basically asking "what's the best way to write commercial software", and if you ask 5 guys you'll get 8 answers.

Therefore, the best answer I can give to such a broad question (not sure it's "overly broad" and thus a candidate for closure, and thus I will try to answer) is:

IT DEPENDS.

It depends on how many developers are working together. In a smaller development environment, say in a medium-sized business that insources a lot of custom app development, there may be a lot of projects that need to get done and very few programmers to do them. In that case the IT manager usually hands each project to one, maybe two developers and say "get this done, do as good a job as you can but I need it in a month". This is usually a pretty free-flowing environment in which self-starting "lone wolf" programmers can thrive. However, in such an environment there tends to be a lot of competing frameworks brought in independently of each other by developers who don't sit down and talk about unified structure. Code quality can suffer, and code often doesn't adhere to any one "manual of style" other than maybe what's defaulted by the IDE.

On the other hand, code houses generally organize into teams, throwing as many people as the schedule and budget for the project call for. These teams require not only self-starters, but good team players who communicate with each other and collaborate. This provides the "synergy" that managers love to talk about, increasing velocity. But, that requires the entire team to be humming along like a well-oiled machine, and to have a project manager that is good at keeping the development roadmap free of obstacles.

It depends on how many projects need to be developed concurrently. Generally it's a good idea to keep one team working on one thing until they're done, then reevaluate the team's size and makeup before assigning the next big thing. Keeping a team doing one thing keeps them focused. However, the more people per team, the fewer teams you have, all other things being equal. That increases the velocity of the team on one thing but may decrease overall throughput. Incorporating work items from other projects into the schedule for a team gets the small things done but takes the focus off the main project, causing a reduction in velocity caused by mental gear-shifting. Small teams reduce velocity but increase the number of concurrent "pipelines", reducing time that items sit in the backlog with other department heads going "why haven't you started work on my project?".

It depends on the scope and budget of projects. If a client needs one developer to augment a site that their in-house UX guy has wireframed, and they need it in a month for $10 grand, and all those constraints are feasible, there's no point in assigning an entire dev team to it; it's not what the client ask for, what they need, nor what they are willing to pay for. Conversely, having a one-dev team work on the next in-house superproject is not a really good idea if you can help it; not only will development be slowed because only one guy's coding it, you're only getting one developer's perspective on the solution which is by its nature going to be a limited one.


问:
Should Developers Perform All Tasks or Should They Specialize?
Disclaimer: The intent of this question isn't to discern what is better for the individual developer, but for the system as a whole.

I've worked in environments where small teams managed certain areas. For example, there would be a small team for every one of these functions:

UI

Framework code

Business/application logic

Database

I've also worked on teams where the developers were responsible for all of these areas and more (QA, analsyt, etc...). My current environment promotes agile development (specifically scrum) and everyone has their hands in every area mentioned above.

While there are pros and cons to each approach, I'd be curious to know if there are more pros and cons than I list below, and also what the generally feeling is about which approach is better.

Devs Do It All

Pros

1. Developers may be more well-rounded

2. Developers know more of the system

Cons

1. Everyone has their hands in all areas, increasing the probability of creating less-than-optimal results in that area

2. It can take longer to do something with which you are unfamiliar (jack of all trades, master of none)

Devs Specialize

Pros

1. Developers can create policies and procedures for their area of expertise and more easily enforce them

2. Developers have more of a chance to become deeply knowledgeable about their specific area and make it the best it can be

3. Other developers don't cross boundaries and degrade another area

Cons

1. As one colleague put it: "Why would you want to pigeon-hole yourself like that?" (Meaning some developers won't get a chance to work in certain areas.)

It's easy to say how wonderful agile is, and that we should do it all, but I'm somewhat of a fan of having areas of expertise.  Without that expertise, I've seen code degrade, database schemas become difficult to manage, hack UI code, etc... Let's face it, some people make careers out of doing just UI work, or just database work. It's not that easy to just fill in and do as good of a job as an expert in that area.

答:
The system doesn't create value. The individual does.

More importantly, a programmer's economic value is directly related to their expertise and ability to adapt to changing circumstances.

I can't think of anytime where it's good to just be a 'Java Developer' or a "C# developer' or a "JavaScript developer". Imagine how the people who defined themselves as 'Cobol developers' now feel? (Besides rich).  Or even better, how the people who defined themselves as Mumps developers now feel?

I used to think that developers should specialize (ironically, when I worked at a job where we didn't specialize).  Now that I work somewhere where we have developers specialize (there's a clear division between FEWD and Back-end development), I wish we didn't.

Regardless of the language and the platform, there are common problems. When you silo yourself to 'front end' or 'back end', you run the risk that one group will make the same mistakes the other group just solved themselves.  Anything can be improved with communication, but the problem can't be fixed if the developers don't have a frame of reference for fixing it.

Even if you have people who are 'better' at front end technologies, it can't do anything but help your business as a whole if developers are familiar with all aspects of their infrastructure and code.  They don't have to become the 'go-to' person, but they do need to be familiar with it.  Otherwise, what happens when one of them gets hit by a bus, or worse, the whole team?


答:
As usually, nobody in practice does things 100% one way or 100% the other, even if they might take that position in an argument for the sake of simplicity.

You mentioned Agile, and Agile does generally tend towards less specialization.  This is because everyone is expected to refactor code as they do development, and that is difficult to do if the refactoring must stop at some kind of boundary, such as if it starts touching the code of a specialist who is very far ahead of the other developers in that area.  So, the optimal amount of specialization is lower if that's the way you work.

Your list of pros and cons isn't bad.  I would add a few, personally:

Pro - It's very nice to have somebody who can get things unstuck when really tough problems come up, and for some of those one specialist is worth a dozen generalists.

Con - Developers communicate less because they are working in their specialized areas most of the time.  If so, they don't learn as much from each other and may optimize locally but miss the global picture.  There are also fewer eyes to find bugs or bad designs.

Con - Redundancy has value.  Having more people understand a given bit of code reduces risk of losing key information about the code.

Again, there are costs and benefits in either approach, so each team needs to try to find the trade-off with the maximum value for it's situation.

Title: Should Developers Perform All Tasks or Should They Specialize?

Body:
Disclaimer: The intent of this question isn't to discern what is better for the individual developer, but for the system as a whole.

I've worked in environments where small teams managed certain areas. For example, there would be a small team for every one of these functions:

UI

Framework code

Business/application logic

Database

I've also worked on teams where the developers were responsible for all of these areas and more (QA, analsyt, etc...). My current environment promotes agile development (specifically scrum) and everyone has their hands in every area mentioned above.

While there are pros and cons to each approach, I'd be curious to know if there are more pros and cons than I list below, and also what the generally feeling is about which approach is better.

Devs Do It All

Pros

1. Developers may be more well-rounded

2. Developers know more of the system

Cons

1. Everyone has their hands in all areas, increasing the probability of creating less-than-optimal results in that area

2. It can take longer to do something with which you are unfamiliar (jack of all trades, master of none)

Devs Specialize

Pros

1. Developers can create policies and procedures for their area of expertise and more easily enforce them

2. Developers have more of a chance to become deeply knowledgeable about their specific area and make it the best it can be

3. Other developers don't cross boundaries and degrade another area

Cons

1. As one colleague put it: "Why would you want to pigeon-hole yourself like that?" (Meaning some developers won't get a chance to work in certain areas.)

It's easy to say how wonderful agile is, and that we should do it all, but I'm somewhat of a fan of having areas of expertise.  Without that expertise, I've seen code degrade, database schemas become difficult to manage, hack UI code, etc... Let's face it, some people make careers out of doing just UI work, or just database work. It's not that easy to just fill in and do as good of a job as an expert in that area.


答:
It depends. If your project lends itself to separation, then do that. If your team is well rounded enough to work on everything, then that might be faster. If you have only 2 developers, then they're going to wear a lot of hats. If your problems are very hard, specialization might be required.

Tailor your process to your scenario; that will be how you get the best result.


答:
In any interview, you should also be interviewing the company.  To do that well, you should already know something about the company, having researched them before the interview.

So I would ask questions that tie your knowledge of their company to something you would like to know more about.  Something like:

"I understand that your company is very involved with community activities, such as [random charity]. Can you tell me a little more about that?"

or

"Is it true that you have a policy of [allocating time for individual research]?  How has that worked out?

Title: "Do you have any questions for us?" In an interview

Body: You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>


答:
The ideal team would have both types of developers. You want to have specialists because they'll have the depth of knowledge that the generalist won't have; they can bang out the code quicker, solve the tricky problems better or faster, and so on. You want to have generalists to be across the system, be able to identify the common problems and fix bottlenecks - for example, that minor change in the database might cost a week's worth of front end redesign. You work in a team, each developers skills, weakeness, preferences and pet-hates comes out and you dish the work up accordingly.

And I think the ideal developer will cover both of these bases. You want to generalise enough to be able to build systems rather than components or just 'bits' to help someone else build a system. But you need to specialise enough to have an edge over the next guy - you want to be the best at something, right?

Of course 'specialise' is a spurious term. I could say "I specialise in .NET"; is that a specialisation? In a way, yes because it defines where my skills lie, but it's hardly a niche area and even within .NET there's far too much to be an expert at. On the other hand, I could say "I specialise in XPath" - okay, that's great too, but it's a much narrower specialisation. You can't build much using just XPath, and if you know nothing but XPath then you're usefulness is very limited.

There are so many areas to be across, and there are only so many hours in a day, that you'll never cover all bases. Ideally you would have an range of experience, and areas of expertise within that range.


答:
This will depend on the skill level of developers in the project.

Usually in a web project, if you have a dev with very good skills on jquery/html/css let him/her work on UI and make it pretty. Logically, a dev who enjoys building back-end code and services would be best useful doing that piece of the application.

However, there might be less experienced devs in the team, who may learn form experienced devs in the team.

In another words, if project has mixed skilled people on the team, let them do what they are best at.


问:
When should you use a private/inner class?
To clarify, what I'm asking about is

```<code>public class A{
    private/*or public*/ B b;
}
</code>```

vs.

```<code>public class A{
    private/*or public*/ class B{
        ....
    }
}
</code>```

I can definitely think of some reasons to use one or the other, but what I would really like to see are convincing examples that show that the pros and cons are not just academic.

答:
Private and inner classes are used to increase levels of encapsulation and hide implementation details.

In C++, in addition to a private class, the same concept can be achieved by implementing a class cpp's anonymous namespace. This serves nicely to hide/privatize an implementation detail.

It is the same idea as an inner or private class but at an even greater level of encapsulation as it is completely invisible outside the file's compilation unit. Nothing of it appears in the header file or is outwardly visible in the class's declaration.


答: I ask them what they (the interviewer(s)) find interesting and challenging in their work for that company. </p>


问:
How do I hire testers by giving them a buggy app for testing their efficiency?
My boss wants to recruit testers based on their testing efficiency (number of bugs identified). So, he's shortlisted 5 people and I need to give them an app full of bugs and see how they fare in reporting obvious bugs, and hidden bugs. I know.... it kind of sounds weird. I guess, this is just like the coding world, where you hire a programmer by assessing his/her programming ability (which is a little easier). Once hired, these testers would be testing a java swing app, so their familiarity of testing frameworks/tools is not really required.

So, my question here is - How do I go about finding buggy apps (web/non-web), preferably java ones, that I can have the shortlisted testers have a go at? How would you go about this task if your boss asks you to do so? I am kind of clueless at this point - I googled a bit, thought about finding new apps on sourceforge with lots of bugs, but both approaches didn't work for me.

答:
I actually did this.  I created a buggy calculator.  It's just HTML and JavaScript.  I created it originally to help my father (a QA professional) practice testing.  And because it was fun.  I then used it when interviewing.

I don't just look for # bugs found though.  I look for:

What bugs are found

How methodical is the person in testing

How clearly are the defects communicated

What questions does the tester ask


问:
When using several languages for different projects, how do you keep the different syntaxes straight?
Context: I'm taking several classes this semester in which I'll be coding. Here is a list of possible languages I'll be using:

Java

C (system and embedded level)

C++ (contest programming)

VHDL (for FPGA work)

Python

Scheme

Is it possible to keep all these languages floating around in one's head? How can one code without having to look up reference material every time they start working?

答:
It takes practice to code without looking up the reference materials.  That's not something likely to happen in a semester unless you use the languages a lot.  I recommend keeping a one page quick reference for each language handy.

You should be able to remember the idioms in each language easily - how to write a function, loop, print a value, etc.  Because these come up often in coding so you will be practice them a lot.

What's the harm in using reference materials?


答:
C++ alone is a massive language as is Java. I could reasonably expect a skilled, veteran to remember all of Scheme, Python, or C but there is no shame to be had in using references.

I'd argue that learning generically applicable programming techniques and remembering the elements of style for each language over trying to remember the entire syntax. I'm not sure that's possible in some cases, particularly given how much languages can change.

I work at a technical bookstore and I routinely sell reference manuals to skilled, experienced professionals. Better to have knowledge that there is such a technique for "thing x" and not remember the exact syntax or semantics than to not know that "thing x" exists. That's why these things exist. You are plugging along and think "I know of something that would work nicely here" and perhaps you find it to be wrong for that language but the reference if it's any good and you've a solid grasp on the fundamentals will give you pointers (sometimes literally) toward a solution.

Title: When using several languages for different projects, how do you keep the different syntaxes straight?

Body:
Context: I'm taking several classes this semester in which I'll be coding. Here is a list of possible languages I'll be using:

Java

C (system and embedded level)

C++ (contest programming)

VHDL (for FPGA work)

Python

Scheme

Is it possible to keep all these languages floating around in one's head? How can one code without having to look up reference material every time they start working?


答:
If you want to do this, create your own buggy app. When I was hired into my current position, I was given an app to test and find bugs that was based on actual software the company worked on. Some of the bugs were pretty obvious, some were more subtle, but mostly here were plenty of bugs or arguably buggy behaviour. My two cents: while this can be fun, it doesn't necessarily make for a good screen of one's testing abilities. Finding obvious bugs in a simple and small application isn't generally too challenging. </p>

<p>If you want to step things up a notch, both for yourselves and the applicants, find real apps and webpages and ask candidates to look for bugs within them. Not only will bugs be usually less obvious, but it may also lead to some enlightening conversations that give some insight into the applicant's thought processes and evaluation skills. It may also force you and your colleagues to up your testing abilities and bug finding skills. But remember, even real-life apps have bugs and issues with them, so finding buggy apps shouldn't be too tall a task. </p>

Title: How do I hire testers by giving them a buggy app for testing their efficiency?

Body:
My boss wants to recruit testers based on their testing efficiency (number of bugs identified). So, he's shortlisted 5 people and I need to give them an app full of bugs and see how they fare in reporting obvious bugs, and hidden bugs. I know.... it kind of sounds weird. I guess, this is just like the coding world, where you hire a programmer by assessing his/her programming ability (which is a little easier). Once hired, these testers would be testing a java swing app, so their familiarity of testing frameworks/tools is not really required.

So, my question here is - How do I go about finding buggy apps (web/non-web), preferably java ones, that I can have the shortlisted testers have a go at? How would you go about this task if your boss asks you to do so? I am kind of clueless at this point - I googled a bit, thought about finding new apps on sourceforge with lots of bugs, but both approaches didn't work for me.

Body:
If you want to do this, create your own buggy app. When I was hired into my current position, I was given an app to test and find bugs that was based on actual software the company worked on. Some of the bugs were pretty obvious, some were more subtle, but mostly here were plenty of bugs or arguably buggy behaviour. My two cents: while this can be fun, it doesn't necessarily make for a good screen of one's testing abilities. Finding obvious bugs in a simple and small application isn't generally too challenging.

If you want to step things up a notch, both for yourselves and the applicants, find real apps and webpages and ask candidates to look for bugs within them. Not only will bugs be usually less obvious, but it may also lead to some enlightening conversations that give some insight into the applicant's thought processes and evaluation skills. It may also force you and your colleagues to up your testing abilities and bug finding skills. But remember, even real-life apps have bugs and issues with them, so finding buggy apps shouldn't be too tall a task.


问:
Is it possible to outsource design properly?
I work in a company going through a downsizing process. It is assumed that a lot of "let go" developers jobs will eventually be outsourced. Some of those programmers had some design to do.

Is it possible to outsource both design and creation/coding properly? I feel that by outsourcing design, we lose any in-house capability of really "owning" the code. It will be very difficult to maintain. Also we'll have a hard time ensuring a proper development.

How can I address those issues?

答:
In regards to maintenance, outsourced is not fundamentally different from employee turn over -- either way, you have someone working on a program which they neither wrote nor designed, and that will probably happen sooner or later.

That said, as long as you have some in-house developers, it is probably better to have them work on the project, even if their role is limited.  That way you can hit the ground running when it's time for the hand off (and your in house developer probably has a better grasp of your domain).


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答:
If there is a good high level design document, I'll use it.  It has to be concise and up to date.  If it's too verbose or out of date, I'll head for the code.

Of course, it depends on the project, doesn't it?  An extremely complex or many-faceted project is perhaps better approached through documentation (if the documentation is solid enough.)

A single simple module or simple application is, in my opinion, almost always best approached at the code level.

There is no right answer for every situation!


问:
What am I missing about PHP?
It's like this mythical thing that a dominating portion of developers say is just the best option for back-end development, a part of development about which I know virtually nothing beyond the absolute basics.

So I've looked up PHP tutorials a bunch of times, trying to figure out why it's so powerful and common, but it's annoying as hell-- all the tutorials treat you like a new programmer. You know, this is how you make an If Else statement, here's a for loop, etc. The "Advanced Topics" show you how to make POST and GET statements and whatnot.

But there must be more to it! I don't get it! That's practically no different from JavaScript. What am I missing about this language? What else can it do? Where's the power and versatility? I've heard it called a function soup; where are all the functions?

Please chide me. I'm clearly missing something.

答:
Check out http://www.php.net/manual/en/

It's tough to really list all the things you can do with server-side code over client-side code, although if someone else made such a list I would find it really interesting.  It's certainly very easy to think of things that you should do on the server-side, since on the client side anyone can read and modify your code.

Title: What am I missing about PHP?


答:
I think the main advantage of PHP, at this stage of the game, is the huge collection of frameworks, libraries, utilities, templating engines and extensions, all designed around server-side internet applications. Similar to how Java had, for years, a very wide ecosystem of tools that made it more interesting than C#, for instance, despite the fact that the language itself wasn't as good as C# (IMO).

It's a bit of a chicken-and-egg situation, since the value of PHP is in its popularity, how did it get so popular? Well, that's a combination of factors, including low barrier of entry (like VB in the 90's) due to being very flexible about the code it accepts, no matter how ugly, and a lack of language that were really web-app driven when it started.

Title: What am I missing about PHP?

Body:
It's like this mythical thing that a dominating portion of developers say is just the best option for back-end development, a part of development about which I know virtually nothing beyond the absolute basics.

So I've looked up PHP tutorials a bunch of times, trying to figure out why it's so powerful and common, but it's annoying as hell-- all the tutorials treat you like a new programmer. You know, this is how you make an If Else statement, here's a for loop, etc. The "Advanced Topics" show you how to make POST and GET statements and whatnot.

But there must be more to it! I don't get it! That's practically no different from JavaScript. What am I missing about this language? What else can it do? Where's the power and versatility? I've heard it called a function soup; where are all the functions?

Please chide me. I'm clearly missing something.


答:
PHP is terrible. For more information you can check Php a fractal of bad design
I have been working with it close to 13 years now, the last 5 not as a hobby, not even dared to jump deep into its OO capabilities, and I am still finding bugs, gotchas, ahas and plain insane behavior on daily basis.

So if you want to find something unique in PHP that elevates it beyond the other languages - there isn't. So why it became the alpha dog then:

You have no choice - unless you start a project from scratch there is usually something already written in PHP that works. (inertia)

It was extremely easy to prototype and iterate - this is more of a historical reason, there are other languages that are good at that now, but c. 1999 there weren't many of them.

Played nice with apache, mysql and was free - maybe the most important thing in this list.

Hosting was easy to find

Easy database access - there were dark times when there were such things as DAO with wild recordsets out to get you. For a mfc developer the idea that your whole DB layer was mysql_connect, mysql_query with simple sql was a godsend.

Simple tool for a simple task - php is really good at getting data from a DB and putting it in a punched hole in your html. And at the dawn of time that was website development.

Title: What am I missing about PHP?


答:
The big reason for PHP's popularity can also be attributed to its ease of use. Anyone (quite literally) can program simple PHP after checking out a few examples of code and trying it a few times. Other web programming languages require a whole lot more effort to create even the simplest of programs, and barring C and Java, there's not much in the way of online examples. Most people don't want to install humongous IDEs, build a dedicated web server, and arrange for a DNS, when all they want is to spice up their website with some extra features. Perhaps they have heard enough horror stories about Javascript that they want to use something else.

In comes PHP. No IDE required, just any regular text editor that comes pre-installed in pretty much all computers. Then just upload a couple of files to a web host, maybe adjust permissions for a few files, and that's it. Fire and forget, if you please. Certainly not pretty or elegant, but it works and is quick. Testing is just pressing F5, without any compiling, delivering, and deploying.

For something more elaborate, just a quick install of WAMP/LAMP, and change a couple of settings in a text file, and off you go in the comfort of your home computer in an environment that is almost "real", so you can easily see the changes on the fly.

I highlighted a few points which I feel are the biggest reason for PHP's popularity.

Title: What am I missing about PHP?


问:
Questions to ask before someone leaves
Apart from the obvious questions relating to specific project work someone is working on are there any questions I should be asking a fellow dev who is leaving the company?

So far I am thinking about;

Locations of things on the server he uses that not maybe everyone does.

Credentials he has set up that we wouldn't have needed.

Client details he has not yet saved into our CRM system.

答:
"Can we have the office key back before you leave."

We have a large open plan office, and a key system that uses expensive keys.  It is a major drama if someone leaves without handing back their key.  Building management hates getting new keys cut for new staff members.

So we had one guy leave without handing in his key.  We bugged him about it, and he eventually put it in an envelope and posted it to us ... or so he says.  What we actually got was an envelope which just contained a PostIt note with a cryptic message.  ("It wasn't me, it was a one armed man").

Finally we figured out what must have happened.  The envelope had been through the Post Office's automatic sorting machines and the key had come out.  So we ring up the Post Office, faxed them a photocopy of a similar key, and got them to look through their pile of "keys that have fallen out of envelopes".  (Apparently they have LOTS of keys ...)  After two weeks, the answer comes back..  They cannot find it.

So now we may need to get the office lock changed ... and 15+ expensive new keys cut ... sigh.

The upside is that one of our younger staff members now understands the "one armed man" reference.

Title: Questions to ask before someone leaves


问:
Are Java certifications important for an architect role?
I want to know how much Java Certifications (SCJP, SCWCD and others) are important for an architect position. If a person posses a good experience in Java development and want to pursue his career on architect level, do you guys think he need to have certification on his CV. If he has never worked on lead developer roles?

If you conducting my interview for an architect position. And I have worked as a Java web developer in different teams having 5 years of exp. Never lead any. And I am having certification badges on my CV.

How can a developer make his career path towards being an architect in a team?

答: Atleast in the corporate world a person with certification always has the edge over the person who doesnt, not necessarily knowlege/skill wise but it as the corporates say it shows initiative.</p>


答: One of uses for private static inner class is Memo pattern. You put all data that needs to be remembered into private class and return it from some function as Object. Noone outside cannot (without reflection, deserialization, memory inspection ...) look into it/modify it, but he can give it back to your class and it can restore its state.</p>

Title: When should you use a private/inner class?

Body:
To clarify, what I'm asking about is

```<code>public class A{
    private/*or public*/ B b;
}
</code>```

vs.

```<code>public class A{
    private/*or public*/ class B{
        ....
    }
}
</code>```

I can definitely think of some reasons to use one or the other, but what I would really like to see are convincing examples that show that the pros and cons are not just academic.


答:
Suppose you're building a tree, a list, a graph and so on. Why should you expose the internal details of a node or a cell to the external world?

Anyone using a graph or a list should only rely on its interface, not its implementation, since you may want to change it one day in the future (e.g. from an array-based implementation to a pointer-based one) and the clients using your data structure (each one of them) would have to modify their code in order to adequate it to the new implementation.

Instead, encapsulating the implementation of a node or a cell in a private inner class gives you the freedom to modify the implementation any time you need to, without the clients to be forced to adjust their code consequently, as long as your data structure's interface remains untouched.

Hiding the details of your data structure's implementation also leads to security advantages, because if you want to distribute your class you'll make only the interface file available together with the compiled implementation file and nobody will know if you're actually using arrays or pointers for your implementation, thus protecting your application from some kind of exploitation or, at least, knowledge due to the impossibility to misuse or inspect your code. In addition to practical issues, please do not underestimate the fact that it's an extremely elegant solution in such cases.


问:
Is there any Common Name for Edit,Save,Delete,Select
Can anyone suggest me a Common Name for Edit,Save,Delete,Select

I want to create a Interface in C#, which will support all these methods.

My Context is :

I am developing an Invoice Application in which i need a Product to be Created,Deleted,Updated,Selected

答:
CRUD is usually the technical term that is used to describe create/read/update/delete functionality.

...create, read, update and delete (CRUD) (Sometimes called SCRUD with an "S" for Search) are the four basic functions of persistent storage. Sometimes CRUD is expanded with the words retrieve instead of read, modify instead of update, or destroy instead of delete. It is also sometimes used to describe user interface conventions that facilitate viewing, searching, and changing information; often using computer-based forms and reports... The acronym may be extended to CRUDL to cover listing of large data sets which bring additional complexity such as pagination when the data sets are too large to hold easily in memory.

Another variation of CRUD is BREAD, an acronym for "Browse, Read, Edit, Add, Delete"...


问:
What to learn after standard C++?
I switched to C++ a few months ago, learning its syntax, the main features
of the STL and what you can usually find in a "learn C++" manual.

Now I would like to go further. What would be your recommendations? I would like to know what to learn next (not only about the language, but also debugging, frameworks etc. etc.)
I know probably the answer depends on the specific needs of each user, so here is a list of mine:

Cross Platform development

Developing GUI for my programs

Develop extendible software, allowing the use of plugins

Use of scientific libraries

Interact with databases (mainly MySQL)

Having server/client functionalities (I'd like users of my programs to interact through internet.. as you might have guessed I am not a programmer by training so I might have used the wrong terms.. if so I apologize for that).

Of course I know it takes time, but I would like to have a good list of references and resources to start (both books and websites are ok).

Thanks a lot for your help!

答:
If there's one thing I could recommend, it'd definitely be Boost C++ Libraries. In fact, Boost is not a single library. It's a collection of them, and they're high-quality, portable, open source and well praised by people ranging from students to the C++ standards committee.

Since Boost does not include GUI or anything else which is platform-dependent, there's also Qt, the cross-platform UI framework. Qt supports almost every single computing platform around nowadays, Linux, Windows, Mac, as well as Symbian and Windows Phone platforms. Since the recent acquisition of Qt by Digia, there are plans to introduce Qt on iOS and Android platforms too. So Qt is most definitely what you want to get familiar with, when it comes to cross-platform UI development.

A further word about C++ itself; as you most probably know, C++11 is the current C++ standard. C++11 almost makes it feel as if it was a new language altogether. Getting familiar with it's new features will take time, so I would also consider focusing on learning some of the new things here and there. Especially some the new standard library additions such as smart pointers are something you might really get used to. Not that they're hard, not at all. Just that they're so important for the sake of safety.

Although this isn't exactly what you asked for, C++ is a vast language. Hard to master, yet it's mastery is very crucial in order to produce effective, safe, obvious and most importantly easy to understand code. Frankly, I'd start by reading Scott Meyers' Effective C++ and More Effective C++ if you haven't already. Sure, neither covers C++11(the fourth edition of Effective C++ will do that, but probably in 2014 or so), but they are extremely valuable to any uprising C++ programmers. Read them. Also C++ Coding Standards by Herb Sutter and Andrei Alexandrescu might come in handy.

Title: What to learn after standard C++?


问:
What's the simplest way to provide a portable, locally running webservice server application?
We have a large website running that offers a JsonRpc web service.

For offline demonstration purposes, I want to realize a portable, locally running webserver with a minimalistic feature replication of the live webservice, and bundle this together with Html files which do Ajax requests to it.
This local server executable should have as little dependencies as possible.

It's going to be run and presented by non-devs on non-dev Windows machines, so I would prefer having a simple executable plus the service code.  The language would need to be .NET, PHP or Java.

I'll need a small database behind which probably will be Sqlite.

It's important to say that, for reasons I won't get into here, we cannot use the original web service code, but we have to rewrite it new for the local demo server. This is why I want to put minimal effort in the local server tech.

An installer for distribution is not mandatory, it's okay to have a zip file with an executable in it which starts up the local webserver.

What would you recommend realizing these requirements?

答:
Thanks for all your suggestions!

Finally I decided to go with the Mongoose stand-alone webserver which supports all kind of cgi plugins, including PHP.
It's easily configurable and deployable and just fits my needs.

On my research I also found the UltiDev Web Server Pro, which was on the short list if I'd decided to go with .NET. Seems to be a nice product, but havn't worked with it yet, maybe it comes in handy for anyone who reads this.

The reason to go with PHP was that it requires a lot smaller footprint than .NET would have needed - in terms of files in the file system. I can put everything I need on the server side into one PHP file, no need for DLLs and other dependencies.

Cheers.


答: The rule I would use is one ViewModel per View. If it's something very generic, than it's a Control rather than a specific View. In that case it would use parent View's DataContext. MessageBox warnings could also be shown using some sort of Service class that you would inject into ViewModels. ViewModels can also have other ViewModels nested in them, for example when you are using Grid-like controls.</p>

Title: MVVM - child windows and data contexts

Body:
Should a child window have it's own data context (View-Model) or use the data context of the parent?  More broadly, should each View have its own View-Model?  Are there are any rules to guide making that decision?  What if the various View-Models will be accessing the same Model?

I haven't been able to find any consistent guidance on my question.  The MS definition of MVVM appears to be silent on child windows.

For one example, I have created a warning message notification View.  It really didn't need a data context since it was passed the message to display.  But if I needed to fancy it up a bit, I would have tapped the parent's data context.

I have run into another scenario that needs a child window and is more complicated than the notification box.  The parent's View-Model is already getting cluttered, so I had planned on generating a dedicated VM for the child window.  But I can't find any guidance on whether this is a good idea or what the potential consequences may be.

FWIW, I happen to be working in Silverlight, but I don't know that this question is strictly a Silverlight issue.


问:
How are Java ByteBuffer's limit and position variable's updated?
There are two scenarios: writing and reading

Writing:

Whenever I write something to the ByteBuffer by calling its put(byte[]) method the position variable is incremented as: current position + size of byte[] and limit stays at the max.

If, however, I put the data in a view buffer then I will have to, manually, calculate and update the position

Before I call the write(ByteBuffer) method of the channel to write something, I will have to flip() the Bytebuffer so that

position points to zero and limit points to the last byte that was written to the ByteBuffer.

Reading:

Whenever I call the read(ByteBuffer) method of a channel to read something, the position variable stays at 0 and the limit variable of the ByteBuffer points to the last byte that was read. So, if the ByteBuffer is smaller than the file being read, the limit variable is pushed to max

This means that the ByteBuffer is already flipped and I can proceed to extracting the values from the ByteBuffer.

Please, correct me where I am wrong :)

答:
Whenever you read from or write to the buffer, only it's position changes.

So you are wrong about reading from channel. Note that reading from channel means writing to the buffer. You can set the position to 0 and limit - to the maximum number of bytes to read before you call Channel.read(ByteBuffer). The read operation then updates the position to the number of bytes actually read. So, to start reading from buffer you have to call ByteBuffer.flip().


答: IMHO there is no really good common name for those operations. Besides the suggestions of the commenters to give your interface a name related to the kind of objects you want to use it for in your context, you could call the interface something like IEditableSaveableDeleteable or IEditableSaveable (the latter assumes when something is saveable that it should be clear in your context that it must also be deleteable).

Title: Is there any Common Name for Edit,Save,Delete,Select

Body:
Can anyone suggest me a Common Name for Edit,Save,Delete,Select

I want to create a Interface in C#, which will support all these methods.

My Context is :

I am developing an Invoice Application in which i need a Product to be Created,Deleted,Updated,Selected


答:
Since you have not given a context of edit, save and delete, I will use the term OBJECT which you would eventually replace to suit your context.

Next, edit, save and delete are each some kind of change. So, it makes your interface to begin with the word Modify.

The third parameter which will be useful in a name is the subject. "Who is changing it?" I will use the term SUBJECT in the name which you would need to replace suitably.

All combined here is my suggestion:

IModify*OBJECT*By*SUBJECT*

Ex. IModifyFileBySuperuser or IModifyUserByAdmin

Hope this helps.


答:
Besides boost and Qt (which is a good suggestion), you could also learn a new programming language. Currently, the most popular cross-platform languages matching your list are Java, Perl, Python and Ruby (though the 3 latter ones are not so strong supported with tools on the GUI development side).

Learning a new language will also give you insides about the strengths and weaknesses of C++, so you don't become a "one trick pony".

Title: What to learn after standard C++?

Body:
I switched to C++ a few months ago, learning its syntax, the main features
of the STL and what you can usually find in a "learn C++" manual.

Now I would like to go further. What would be your recommendations? I would like to know what to learn next (not only about the language, but also debugging, frameworks etc. etc.)
I know probably the answer depends on the specific needs of each user, so here is a list of mine:

Cross Platform development

Developing GUI for my programs

Develop extendible software, allowing the use of plugins

Use of scientific libraries

Interact with databases (mainly MySQL)

Having server/client functionalities (I'd like users of my programs to interact through internet.. as you might have guessed I am not a programmer by training so I might have used the wrong terms.. if so I apologize for that).

Of course I know it takes time, but I would like to have a good list of references and resources to start (both books and websites are ok).

Thanks a lot for your help!


问:
What are the advantages of Ceylon over Java?
Looking for the recent and powerful upcoming programming languages over net, I came across Ceylon. I dropped in at ceylon-lang.org and it says:

Ceylon is deeply influenced by Java. You see, we're fans of Java, but we know its limitations inside out. Ceylon keeps the best bits of Java but improves things that in our experience are annoying, tedious, frustrating, difficult to understand, or bugprone.

What are the advantages of Ceylon over Java?

答:
Ceylon is producing a specification during its development, like all the big JVM languages (i.e. all those mentioned above except Groovy)...

Ceylon (http://ceylon-lang.org/documentation/1.0/spec)

Clojure (http://clojure.org/Reference)

Scala (www.scala-lang.org/docu/files/ScalaReference.pdf)

Java (http://docs.oracle.com/javase/specs/jls/se7/html/index.html)

JRuby follows Ruby's spec which must be paid for (http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=59579).


答:
The language itself is not very exciting, the functions are "grown organically", you probably have heard of the inconsistencies in parameter order.

The power for backend development comes in when you don't do everything yourself but use one of the existing (PHP 5.3) frameworks. I recommend Symfony 2, but also have a look at Zend Framework, CodeIgniter and CakePHP to see if their framework style fits with your programming style. You'll get foundational stuff like  session handling, caching, authentication, separation of data, presentation and action layer (MVC), etc.

Title: What am I missing about PHP?


问:
MVVM - child windows and data contexts
Should a child window have it's own data context (View-Model) or use the data context of the parent?  More broadly, should each View have its own View-Model?  Are there are any rules to guide making that decision?  What if the various View-Models will be accessing the same Model?

I haven't been able to find any consistent guidance on my question.  The MS definition of MVVM appears to be silent on child windows.

For one example, I have created a warning message notification View.  It really didn't need a data context since it was passed the message to display.  But if I needed to fancy it up a bit, I would have tapped the parent's data context.

I have run into another scenario that needs a child window and is more complicated than the notification box.  The parent's View-Model is already getting cluttered, so I had planned on generating a dedicated VM for the child window.  But I can't find any guidance on whether this is a good idea or what the potential consequences may be.

FWIW, I happen to be working in Silverlight, but I don't know that this question is strictly a Silverlight issue.

答: I feel like any child view should have its own view model. I say this because if you were you take out the child view from the parent view you would have redundant data (which was intended for the child view) sitting in the parent view model. It seems to me that for this reason alone it would make the most sense to have a view model for each. </p>

Title: MVVM - child windows and data contexts


答:
Is it possible to outsource both design and creation/coding properly?

Of course it is. There are many, many firms whose business model depends on it.

I feel that by outsourcing design, we lose any in-house capability of
  really "owning" the code. It will be very difficult to maintain.

That may or may not turn out to be true, depending on the relationship between your company and whoever it hires to do the work. Do you expect to hire contractors to come in and work with your team on projects? Or will you send a description of a problem and a list of requirements off to some company and expect to get back a finished product?

The decision to do less development in house has apparently already been made, so assume that the folks who make the decisions are willing to live with having less that total control over and knowledge of the software development that you do.

Title: Is it possible to outsource design properly?

Body:
I work in a company going through a downsizing process. It is assumed that a lot of "let go" developers jobs will eventually be outsourced. Some of those programmers had some design to do.

Is it possible to outsource both design and creation/coding properly? I feel that by outsourcing design, we lose any in-house capability of really "owning" the code. It will be very difficult to maintain. Also we'll have a hard time ensuring a proper development.

How can I address those issues?


问:
OO Software Architecture - base class that everything inherits from. Bad/good idea?
I am reviewing a proposed OO software architecture that looks like this:

Base

Foo

Something

Bar

SomethingElse

Where Base is a static class.

My immediate thought was that every object in any class will inherit all the methods in Base which would create a large object.  Could this cause problems for a large system?  The whole architecture is hierarchical.. the 'tree' is much bigger than this really.  Does this sort of architecture have a name (hierarchical?!).  What are the known pros and cons?

答: Having each class inherit from a single base class might create a large object depending on what you put in the base class. But, the advantage of this is that all the utility type of functions can be put in the base class and this will offer uniform implementation.</p>


答:
I'm not sure if such architecture has a name, but this is exactly what Microsoft has done (except that not all the methods in the base class are static). In C#, for instance, every type is inherited from the Object class. So every type has methods like Equals(...), GetHashCode() etc. In many MVC applications there is base controller, which is inherited by all controllers.

This approach has a lot of advantages. Here are some of them:

common interface for all objects

a set of mandatory features, which now every object will have

flexibility: new common features can be easily added

etc.

The disadvantage is that there might be objects which will never need these methods, but will still inherit them. Though this disadvantages can be easily ignored.

Title: OO Software Architecture - base class that everything inherits from. Bad/good idea?

Body:
I am reviewing a proposed OO software architecture that looks like this:

Base

Foo

Something

Bar

SomethingElse

Where Base is a static class.

My immediate thought was that every object in any class will inherit all the methods in Base which would create a large object.  Could this cause problems for a large system?  The whole architecture is hierarchical.. the 'tree' is much bigger than this really.  Does this sort of architecture have a name (hierarchical?!).  What are the known pros and cons?


问:
Have I mistakenly assumed that my routines are loosely coupled?
My Selenium test structures goes as -

Data Object class -

```<code>public class RegistrationData {

  String firstName = "test first name";
  String lastName = "test last name";

  // Getter Setter Here
}
</code>```

Page Object class which carries out operations on a Web Page -

```<code>public class RegistrationPage {
   private RegistrationData regData;

   public void setRegistrationData(RegistrationData regData) {
   this.regData = regData();

   public NewAccountPage fillRegForm() {
     enterFirstName("FirstNameTextBoxLocator", regData.getFirstName);
     enterLastName("LastNameTextBoxLocator", regData.getLastName);
     // Some more fields are filled here
     return NewAccountPage();
   }
}
</code>```

And test class uses them as -

```<code>public class TestRegistration extends SelTestCase {

   @Test
   public void testRegNewUser() {
     RegistrationData regData = new RegistrationData();
     RegistrationPage regPage = New RegistrationPage();
     regPage.setRegistrationData(regData)
     regPage.fillRegForm();
     // Some assertion here
   }
}
</code>```

Now since fillRegForm method does not take any argument, Can I assume that it is an example of loose coupling despite I need to set RegistrationData in RegistrationPage before being able to use fillRegForm method.

答:
As far as I can tell, your example closely matches the strong coupling, as it is defined in Wikipedia:

Strong coupling occurs when a dependent class contains a pointer directly to a concrete class which provides the required behavior. The dependency cannot be substituted, or its "signature" changed, without requiring a change to the dependent class. Loose coupling occurs when the dependent class contains a pointer only to an interface, which can then be implemented by one or many concrete classes. The dependent class's dependency is to a "contract" specified by the interface; a defined list of methods and/or properties that implementing classes must provide. Any class that implements the interface can thus satisfy the dependency of a dependent class without having to change the class. This allows for extensibility in software design; a new class implementing an interface can be written to replace a current dependency in some or all situations, without requiring a change to the dependent class; the new and old classes can be interchanged freely. Strong coupling does not allow this...

Let's look at the code from the perspective of above definition:

check

dependent class contains a pointer directly to a concrete class which provides the required behavior

In your example, dependent class is RegistrationPage and direct pointer to a concrete class it contains is RegistrationData regData.

check

dependency cannot be substituted, or its "signature" changed, without requiring a change to the dependent class

In your example, one would have to change RegistrationPage in order to use some other source than RegistrationData class to pass the data to enterFirstName and other methods.

In layman terms, RegistrationPage "knows" quite a lot about RegistrationData - it knows that such a class exists and it knows essential members of this class. This kind coupling is anything but loose.

I assume that I need interface of RegistrationData class to be used in RegistrationPage class. Is not it?

Interface of RegistrationData would make it loosely coupled. As for whether you need it or not, it depends on the context and largely, also on your personal / team preferences. For example as explained in my other answer, I would likely try to avoid having such interface if RegistrationData was a single implementation.

I am indeed asking suggestion for redesign now and please let me know if I need to add more details to question.

This means your original question whether it's loose coupling is solved right? As for redesign, that would be a different question, consider posting it separately.


问:
What is a "wrapper" program?
Where I work, employees use a third-party desktop program for their clients. This program saves data to a flat file. My colleague wants to write a Java program that uploads that flat file to a remote server, opens the desktop program when the flat file is downloaded from a Web site, and checks if the desktop program is running or not by looking at the Windows processes.

He keeps calling this helper/utility program a "wrapper." But it doesn't wrap anything! I tried to clear it up with him, but he said, "Well, I call it a wrapper." He now has everyone in the company calling it a "wrapper." What would you call it? I say that it's a helper program or utility program.

答:
I don't think there's an official definition!  In my mind, a wrapper program is a program that, in general, starts before the wrapped program starts, and exits no earlier than after the wrapped program exits.  A wrapper program would probably also manage the lifetime of the wrapped program (start it for you, stop it for you.)

I recommend against arguing too much over the names of things, though.  The important thing is to design software that works well.  Sometimes belaboring terminology can aid in this goal; sometimes it is a hobgoblin.

Title: What is a "wrapper" program?


问:
Object construction design
I recently started to use c# to interface with a database, and there was one part of the process that appeared odd to me. When creating a SqlCommand, the method I was lead to took the form:

```<code>SqlCommand myCommand = new SqlCommand("Command String", myConnection);
</code>```

Coming from a Java background, I was expecting something more similar to

```<code>SqlCommand myCommand = myConnection.createCommand("Command String");
</code>```

I am asking, in terms of design, what is the difference between the two? The phrase "single responsibility" has been used to suggest that a connection should not be responsible for creating SqlCommands, but I would also say that, in my mind, the difference between the two is partly a mental one of the difference between a connection executing a command and a command acting on a connection, the latter of which seems less like what I have been lead to believe OOP should be. There is also a part of me wondering if the two should be completely separate, and should only come together in some sort of connection.execute(command) method. Can anyone help clear up these differences? Are any of these methods "more correct" than the others from an OO point of view?

(P.S. the fact that c# is used is completely irrelevant. It just highlighted to me that different approaches were used)

答:
Since commands are useless without connections, the fact that the creation of commands is related to an instance of the connection makes sense.

Please note than in addition to the constructor of SqlCommand there is a method called CreateConnection on all IDbConnection instances letting you create a command "Java-style":

```<code>IDbCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = "select * from mytable";
</code>```

This code works with any RDBMS, not only the SQL Server, because an Oracle connection would create an Oracle command, a Sql Server connection would create a SQL Server command, and so on.

The pattern is called a Factory Method, it is instrumental in letting you program to an interface.

Title: Object construction design

Body:
Since commands are useless without connections, the fact that the creation of commands is related to an instance of the connection makes sense.

Please note than in addition to the constructor of SqlCommand there is a method called CreateConnection on all IDbConnection instances letting you create a command "Java-style":

IDbCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = "select * from mytable";

This code works with any RDBMS, not only the SQL Server, because an Oracle connection would create an Oracle command, a Sql Server connection would create a SQL Server command, and so on.

The pattern is called a Factory Method, it is instrumental in letting you program to an interface.


答:
What do you mean when you say "large object"? Memory footprint? That shouldn't really be a problem.

If the methods are static (is that what you mean by "static class"?), they're part of the class, not of each instance. But even if they're instance methods, they shouldn't affect the memory footprint of an object.

If you mean "large object" as in "containing a lot of methods that you rarely use", then... yes, that might be an issue. The shared base class should probably only contain methods that really are shared.

The question is what exactly do you aim to achieve with this architecture? the .NET Framework has a shared Object class, as superM mentioned, but after that, the hiererachy is flat, with most classes inheriting directly (though implicitly) from Object.


问:
Declaring interface in the same file as the base class, is it a good practice?
To be interchangable and testable, normally services with logic needs to have interface, e.g.

```<code>public class FooService: IFooService
{ ... }
</code>```

Design-wise, I agree with this, but one of the things that bothers me with this approach is that for one service you will need to declare two things (the class and the interface), and in our team, normally two files (one for the class and one for the interface). Another discomfort is the difficulty in navigation because using "Go to definition" in IDE (VS2010) will point to the interface (since other classes refer to the interface), not the actual class.

I was thinking that writing IFooService in the same file as FooService will reduce the above weirdness. After all, IFooService and FooService are very related. Is this a good practice? Is there a good reason that IFooService must be located in its own file?

答:
It doesn't have to be in its own file, but your team should decide on a standard and stick to it.

Also, you're right that "Go to definition" takes you to the interface, but if you have Resharper installed, it's only one click to open a list of derived classes/interfaces from that interface, so it's not a big deal.  That's why I keep the interface in a separate file.


答:
The real question is: WHY does the architect want everything to inherit from base? What's the utility of doing so?

If it's for something like serialization interfaces, then it MIGHT make sense if you will need a general serialization facility. But make sure that you actually will need EVERY class in the system to have that functionality. If you don't, then you end up needlessly inflating each class, AND you'll end up having to implement (or stub out) functionality in classes where that functionality doesn't make sense.

I would NEVER implement my own 'uber-base' like this in a system, because I can't conceive of any functionality or interface that I would want in EVERY object EVERYWHERE in my system. The only thing I can think of that it might be useful for is something like heterogeneous containers, but I've never been in a situation where I wanted a completely heterogeneous container - I generally want a set of classes, not just any random thing under the sun to go into my containers.

Unless the architect can demonstrate why they want this uber-base, I'd leave it out.


问:
When should you use a private/inner class?
To clarify, what I'm asking about is

```<code>public class A{
    private/*or public*/ B b;
}
</code>```

vs.

```<code>public class A{
    private/*or public*/ class B{
        ....
    }
}
</code>```

I can definitely think of some reasons to use one or the other, but what I would really like to see are convincing examples that show that the pros and cons are not just academic.

答:
One reason to use a private inner class might be because an API you're using requires inheritance from a particular class, but you don't want to export the knowledge of that class to users of your outer class.  For example:

```<code>// async_op.h -- someone else's api.
struct callback
{
    virtual ~callback(){}
    virtual void fire() = 0;
};

void do_my_async_op(callback *p);

// caller.cpp -- my api
class caller
{
private :
    struct caller_inner : callback
    {
        caller_inner(caller &self) : self_(self) {}
        void fire() { self_.do_callback(); }
        caller &self_;
    };

    void do_callback()
    {
        // Real callback
    }

    caller_inner inner_;

public :
    caller() : inner_(*this) {}

    void do_op()
    {
        do_my_async_op(&inner_);
    }
};
</code>```

In this, the do_my_async_op requires an object of type callback to be passed to it.  This callback has a public member function signature that the API uses.

When do_op() is called from the outer_class, it uses an instance of the private inner class which inherits from the required callback class instead of a pointer to itself. The outer class has a reference to the outer class for the simple purpose of shunting the callback into the outer class's private do_callback member function.

The benefit of this is that you are sure that no-one else can possibly call the public "fire()" member function.

Body:
One reason to use a private inner class might be because an API you're using requires inheritance from a particular class, but you don't want to export the knowledge of that class to users of your outer class.  For example:

// async_op.h -- someone else's api.
struct callback
{
    virtual ~callback(){}
    virtual void fire() = 0;
};

void do_my_async_op(callback *p);

// caller.cpp -- my api
class caller
{
private :
    struct caller_inner : callback
    {
        caller_inner(caller &self) : self_(self) {}
        void fire() { self_.do_callback(); }
        caller &self_;
    };

    void do_callback()
    {
        // Real callback
    }

    caller_inner inner_;

public :
    caller() : inner_(*this) {}

    void do_op()
    {
        do_my_async_op(&inner_);
    }
};

In this, the do_my_async_op requires an object of type callback to be passed to it.  This callback has a public member function signature that the API uses.

When do_op() is called from the outer_class, it uses an instance of the private inner class which inherits from the required callback class instead of a pointer to itself. The outer class has a reference to the outer class for the simple purpose of shunting the callback into the outer class's private do_callback member function.

The benefit of this is that you are sure that no-one else can possibly call the public "fire()" member function.


答:
My immediate thought was that every object in any class will inherit all the methods in Base which would create a large object.

This is incorrect. The reference to the parent type is an extra pointer at worst. If the base type has only methods or static members, it won't add much of anything to the subtype when instantiated.

Could this cause problems for a large system? The whole architecture is hierarchical.. the 'tree' is much bigger than this really.

Deep inheritance hierarchies are a code smell, sure. Having a common base class is often times troublesome because there are very, very few things that apply to everything and behave the same. It often leads to leaky abstractions and violation of the Liskov Substitution Principle.

Where Base is a static class.

This seems a little odd. If the base class is essentially empty from an instance member perspective, that runs into a variety of other issues. At that point specifying a variable of that type allows you to do almost nothing with it, which is...    counterproductive.


问:
"Do you have any questions for us?" In an interview
You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>

答:
The bulk of the interview should have given you an idea what the company does and where they think you fit.  If nothing else from the questions they are asking you they should be fishing for a go/no-go as to you fitting in the position they need.  If the interview was too generic and doesnt explain what the company does from a technical perspective.  Ask.  Interview them as they have just interviewed you.

Secondly, work is not all about the technical topics, the day to day work environment, can I take personal calls (from spouse, kids, friends, etc).  Dress code.  do I get a computer a cube, an office.  Can I install my favorite text editor or other programming software, or am I extremely limited only to what the company provides.  You spend about half of each work day in that chair or stool or whatever they provide you.  Better to know now that you have to have a shaved head and wear a three piece suit every day with no air conditioning and/or heat, get 37 minutes for lunch and are limited to what is available from the snack machine, than to figure this all out after you have committed to the job.

The specific questions to ask in both categories are very specific to you and you wont really figure out what is important (to you) until after you have experienced it.  For each job or each office experience you form a list of what you can tolerate and what you cannot.  Work from that list.


答:
A static base class will allow using of all public or protected functions and members of that base class everywhere through your object hierarchy, without referring to a specific class name (or namespace). This means you will just get global functions and members all throughout your system, which "disables" some of the main ideas of object orientation. You will get a much better architecture when you put those static methods into separate utility classes and group them thematically. Otherwise, such a base class could too easily become a "god class", which is a well-known anti-pattern.

IMHO the whole thing would make sense to a certain degree only if you

don't add any functions or members to the static base class

need a mixed-type generic container for your objects and you don't have any built-in language support for that


答: I personally don't like the "I" in front of an interface. As a user of such a type I'don't want to see that this is a interface or not. The type is the interesting thing. In terms of dependencies your FooService is ONE possible implementation of IFooService. The interface should be near of the place where it is used. On the other hand the implementation should be at a place where it can be easily changed without effecting the client. So, I would prefer two files - normally.</p>

Title: Declaring interface in the same file as the base class, is it a good practice?

Body:
To be interchangable and testable, normally services with logic needs to have interface, e.g.

```<code>public class FooService: IFooService
{ ... }
</code>```

Design-wise, I agree with this, but one of the things that bothers me with this approach is that for one service you will need to declare two things (the class and the interface), and in our team, normally two files (one for the class and one for the interface). Another discomfort is the difficulty in navigation because using "Go to definition" in IDE (VS2010) will point to the interface (since other classes refer to the interface), not the actual class.

I was thinking that writing IFooService in the same file as FooService will reduce the above weirdness. After all, IFooService and FooService are very related. Is this a good practice? Is there a good reason that IFooService must be located in its own file?


问:
How to discriminate commented code and documentation comments
After using version control tools, it is no longer necessary to comment out old code.
However, some team members still comment out old code. Therefore, I want to clean them up.

I want to mark commented lines which are really comments / documentation, so that every time I do not need to re-read all commented regions. The unmarked lines left are new commented code.

How do I achieve this? Any existing tools or need to write on my own?

Similar concept: in git, we have 'partial commit' to select some lines to commit.
However, the lines marked in 'partial commit' is valid once only.

答: Don't mark comments as comments, if you find commented out code while working in a file just delete it. Also try to get those that still insist on commenting out code to stop doing that, nothing is going to change unless you can stop people from commenting out blocks of bad code and not just deleting them. Then its just a simple matter of your team all working together to eliminate commented code when they find it, trying to make those that left commented code go back and clean it up is just a recipe for unnecessary drama.</p>


答:
Why is having separate files a discomfort? For me, it's much neater and cleaner. It's common to create a subfolder named "Interfaces" and stick your IFooServer.cs files there, if you want to see fewer files in your Solution Explorer.

The reason the interface is defined in its own file is for the same reason that classes are usually defined in their own file: project management is simpler when your logical structure and file structure are identical, so you always know which file a given class is defined in. This can make your life easier when debugging (exception stack traces usually give you file and line numbers) or when merging source code in a source control repository.


答:
Be careful, because documentation comments sometimes also contain code examples. You want to keep those. For example:

```<code>/**
  * This class does something.
  * Usage:
  * <code>
  * MyClass.doSomething();
  * </code>
  */
</code>```

There is probably no error-proof method, but you could write a short Perl script that finds all comments in the code, keeps the documentation comments, and then makes a guess about the remaining ones using a few regular expressions for the beginning of the comment.

Title: How to discriminate commented code and documentation comments

Body:
After using version control tools, it is no longer necessary to comment out old code.
However, some team members still comment out old code. Therefore, I want to clean them up.

I want to mark commented lines which are really comments / documentation, so that every time I do not need to re-read all commented regions. The unmarked lines left are new commented code.

How do I achieve this? Any existing tools or need to write on my own?

Similar concept: in git, we have 'partial commit' to select some lines to commit.
However, the lines marked in 'partial commit' is valid once only.

Body:
Be careful, because documentation comments sometimes also contain code examples. You want to keep those. For example:

/**
  * This class does something.
  * Usage:
  * <code>
  * MyClass.doSomething();
  * </code>
  */

There is probably no error-proof method, but you could write a short Perl script that finds all comments in the code, keeps the documentation comments, and then makes a guess about the remaining ones using a few regular expressions for the beginning of the comment.


答:
I think that the "nuke on sight" strategy suggested by @Ryathal is sound.

If you want to detect commented out code (please don't call it "commented code" because lots of people think that means code with comments!) then I think you are going to need to do this by examining the diffs between successive versions. Even then it is not straight forward because there is a variety of ways to comment out code ... depending on the programming language.


答: I think you should keep them separate files. As you said, the idea is to remain testable and interchangeable. By placing the interface in the same file as your implementation, you are associating the interface with the specific implementation. Should you decide to create a mock object or another implementation, the interface will not be logically separate from FooService.</p>


答:
Interfaces belong to their clients not to their implementations, as defined in Agile Principles, Practices and Patterns by Robert C. Martin. Thus, combining interface and implementation in the same place is against it's principle.

Client code depends on the interface. This allows the possibility of compiling and deploying the client code and the interface without the implementation. Than you can have different implementations working like plugins to the client code.

UPDATE:
This is not an agile-only principle here. The Gang of Four in Design Patterns, back in '94, are already talking about clients adhering to interfaces and programming to interfaces. Their view is similar.


答:
It is often a good practice to let your code files contain only a single class, or a single interface. But these coding practices are a means to an end - to better structure your code making it easier to work with. If you, and your team, find it easier to work with if the classes are kept together with their interfaces, by all means do so.

Personally I prefer to have the interface and class in the same file when there is just one class that implements the interface, such as in your case.

In regards to the problems you have with navigation, I can highly recommend ReSharper. It contains some highly useful shortcuts for jumping directly to the method implementing a specific interface method.


答:
It rarely, if ever, makes sense to have a single implementation of an interface1. If you put a public interface and a public class implementing that interface into the same file, good chances are that you do not need an interface.

When the class that you co-locate with the interface is abstract, and you know that all implementations of your interface should inherit that abstract class, locating the two in the same file makes sense. You should still scrutinize your decision to use an interface: ask yourself if an abstract class by itself would be fine, and drop the interface if the answer is affirmative.

Generally, though, you should stick to the "one public class/interface corresponds to one file" strategy: it is easy to follow, and it makes your source tree easier to navigate.

1 One notable exception is when you need to have an interface for testing purposes, because your choice of mocking framework placed this additional requirement on your code.


答: Coding to interfaces can be bad, is in fact treated as an anti-pattern for certain contexts, and is not a law. Usually a good example of coding to interfaces anti-pattern is when you have an interface that only has one implementation in your application. Another would be if the interface file becomes so bothersome that you have to hide its declaration in the implemented class's file.</p>


问:
What techniques are used in solving code golf problems?

"Regular" golf vs. code golf:

Both are competitions.  Both have a well-defined set of rules, which I'll leave out for simplicity.  Both have well-defined goals; in short, "use fewer hits/characters than your competitors."

To win matches, athletic golfers rely on

equipment

Some situations call for a sand wedge; others, a 9-iron.

techniques

The drive works better when your feet are about shoulder width apart and your arms are relaxed.

and strategies

Sure, you could take that direct shortcut to the hole... but do you really want to risk the water hazard or sand bunker when those trees are in the way and the wind is so strong?  It might be better to go around the long way.

What do code golfers have that's analagous to athletic golfers' equipment, techniques and strategies?

Sample answer to get this started: use the right club!  Choose GolfScript instead of C#.

答:
When I do a Code Golf challenge, I inevitably reach for a common set of design patterns that inevitably lead to shorter code: this set increases over time as more code golf challenges are done or just in the course of normal use of a language.

For example, if I need to have an incremental loop, one thing I might do normally is:

```<code>for ($i = 1; $i <= 10; $i++) {
  // code
}
</code>```

or

```<code>$i = 1;

while ($i < 10) {
  // code

  $i++;
}
</code>```

But this always works too:

```<code>while ($i++<10) {
  // code
}
</code>```

Other things include:

Using shorter versions of standard library functions (fwrite() instead of file_put_contents())

Using variables to repeat expressions

taking advantage of how a language handles brackets and line breaks; in most code golfs, the output rarely requires a complex code block spanning more than one line (unless you're using a language where whitespace is substantial)

taking advantage of how a language handles output (<?= shorter than print or echo)

Body:
When I do a Code Golf challenge, I inevitably reach for a common set of design patterns that inevitably lead to shorter code: this set increases over time as more code golf challenges are done or just in the course of normal use of a language.

For example, if I need to have an incremental loop, one thing I might do normally is:

for ($i = 1; $i <= 10; $i++) {
  // code
}

or

$i = 1;

while ($i < 10) {
  // code

  $i++;
}

But this always works too:

while ($i++<10) {
  // code
}

Other things include:

Using shorter versions of standard library functions (fwrite() instead of file_put_contents())

Using variables to repeat expressions

taking advantage of how a language handles brackets and line breaks; in most code golfs, the output rarely requires a complex code block spanning more than one line (unless you're using a language where whitespace is substantial)

taking advantage of how a language handles output (<?= shorter than print or echo)