问:
Command pattern design
I have this old implementation of the Command pattern. It is kind of passing a Context through all the DIOperation implementation, but I realized later on, in the process of learning and learning (that never stops), that is not optimal. I also think that the "visiting" here doesn't really fit and just confuses.

I am actually thinking of refactoring my code, also because a Command should know nothing about the others and at the moment they all share the same key-value pairs. It is really hard to maintain which class owns which key-value, sometimes leading to duplicate variables.

An Example of use case: let's say CommandB requires UserName which is set by CommandA. Should CommandA set the key UserNameForCommandB=John? Or should they share a common UserName=John key-value? What if the UserName is used by a third Command?

How can I improve this design? Thanks!

```<code>class DIParameters {
public:
   /**
    * Parameter setter.
    */
    virtual void setParameter(std::string key, std::string value) = 0;
    /**
    * Parameter getter.
    */
    virtual std::string getParameter(std::string key) const = 0;

    virtual ~DIParameters() = 0;
};

class DIOperation {
public:
    /**
     * Visit before performing execution.
     */
    virtual void visitBefore(DIParameters& visitee) = 0;
    /**
     * Perform.
     */
    virtual int perform() = 0;
    /**
     * Visit after performing execution.
     */
    virtual void visitAfter(DIParameters& visitee) = 0;

    virtual ~DIOperation() = 0;
};
</code>```

答:
I am a bit worried about the mutability of your command parameters. Is it really necessary to create a command with constantly changing parameters?

Problems with your approach:

Do you want other threads/commands to change your parameters while perform is going on?

Do you want visitBefore and visitAfter of the same Command object to be called with different DIParameter objects?

Do you want someone to feed parameters to your commands, that the commands have no idea about?

None of this is prohibited by your current design. While a generic key-value parameter concept has its merits at times, I do not like it with respect to a generic command class.

Example of consequences:

Consider a concrete realization of your Command class - something like CreateUserCommand. Now obviously, when you request a new user to be created, the command will need a name for that user. Given that I know the CreateUserCommand and the DIParameters classes, which parameter should I set?

I could set the userName parameter, or username.. do you treat parameters case insensitively? I wouldn't know really.. oh wait.. maybe it's just name?

As you can see the freedom you gain from a generic key-value mapping implies that using your classes as someone who did not implement them is unwarrantedly difficult. You would at least need to provide some constants for your commands to let others know which keys are supported by that command.

Possible different designs approaches:

Immutable parameters: By turning your Parameter instances immutable you can freely reuse them among different commands.

Specific parameter classes: Given a UserParameter class that contains exactly the parameters I would need for commands that involve a user, it would be much simpler to work with this API. You could still have inheritance on the parameters, but it would not make sense any longer for command classes to take arbitrary parameters - at the pro side of course this means that API users know which parameters are required exactly.

One command instance per context: If you need your commands to have things like visitBefore and visitAfter, whilst also reusing them with different parameters, you will be open to the problem of getting called with differing parameters. If the parameters should be the same on multiple method calls, you need to encapsulate them into the command such that they cannot be switched out for other parameters in-between the calls.

Title: Command pattern design


问:
Building an RPC framework
I'm curious about what it takes to build a simple and robust RPC framework. I've only looked at a few ruby frameworks but they are all lacking in some way. What I want out of an RPC framework is some kind of registration/discovery mechanism and a simple plugin architecture. Pretty much all the frameworks out there provide a simple plugin mechanism but I haven't found one that provides a simple discovery mechanism. The only one that does provide something in terms of discovery is MCollective but that has its own set of issues that I've run into while trying to use it at work.

So how hard would it be to build one from the ground up using tcp sockets or maybe 0MQ? Any issues I should be aware of ahead of time before I start this project?

答:
It's not a matter of whether it would be hard to build one from ground up, but a matter of whether it would be wise. It wouldn't.

Since it seems to be discovery mechanism you are missing, it would be easier to improve or add better discovery mechanism to an existing RPC framework. That would also give you higher chance to actually get users if you wanted to publish it.

Now the problem is that discovery is hard and there is no universal method for discovery that would work in any situation. You can have simply URL, you can have local broker (like D-bus), or network tracker (most peer-to-peer networks), you can have special entries in DNS (preferably DNS-SD), you can have multi-cast and well-known ports or some existing multi-cast based protocol like multi-cast DNS+DNS-SD or Simple Service Discovery Protocol (part of upnp)… You didn't say what you want it for, so I can't unfortunately suggest you any particular solution.

Also don't limit yourself to Ruby; look at existing technology implemented in other languages that could be bound or ported to ruby. One of big advantages of RPC mechanism is that each peer can be implemented in different language, so it's always better if the same protocol is implemented by multiple languages.

ContentLicense: CC BY-SA 3.0

Title: Building an RPC framework


问:
To be strict or pragmatic?
I'm beginning to realize that developing software is (amongst others) a process of constantly asking yourself questions. Questions regarding quality of code, separation of concerns, minimizing dependencies, ...

But the main question is: how far can you go without ending up in a mental hospital?

I'm applying for a new job. Yesterday I was with a possible future employer who wanted to test my programming capablities. One of the exercises was: explain what this code does. I went through some code of the application (winforms in vb.net) that they develop (it's an administrative application for a hospital). This gave me the opportunity to actually see how they approach things and it was rather disappointing.

Some examples:

I saw somewhere: Call [insert name of subroutine here] -> I was struck: isn't that something from VB6?

They have a separate datalayer, using ado.net, but one method I had to examine returns a dataset to the calling layer. So separate datalayer or not, the application is tied to ado.net (which could also never be a problem if they never switch to another data access approach).

That dataset is read as-is, so it still is a data-centric approach (of course, one can argue how much logic/behaviour you can put in classes like "Patient" or "LabAnalysisRequest".

I also believe to have seen the construction of an sql query by string concatenation.

They use stored procedures (which, to me, means: scattering of logic)

no mention of views/controllers: it's all form driven

The most ugly thing I saw was:
    ```
    If TestEnvironment.IsTesting then
       someVar = [some hard coded value]
    else
       someVar = [some dynamically retrieved value]
    end if
    [remainder of the function here]
```

It's all so different from what I learned in school: (persistence agnostic) domain layer, persistence layer, presentation layer, unit testing, ...

So I rephrase my question: how fundamental or dogmatic should one be? To what extent should a programmer stick to his or her principles or just write code that does the job?

答:
how fundamental or dogmatic should one be? To what extent should a programmer stick to his or her principles or just write code that does the job?

The most important thing to remember here is what is your purpose?

In most companies, your purpose in life is not to write perfect code. Your purpose is to deliver value for the user. Writing good code is usually the best way to deliver a good product that is also easy to maintain, trouble shoot and develop.

Good code is a tool which you should apply where it gives you good ROI.

Some examples:

I would spend a lot of time designing and coding my APIs, especially my business tier's API. A lot of other programmers are going to use them and it will save a lot of time and problems if they are properly designed

I will relax the rules a bit in my presentation layer. There I will be more inclined to sacrifice code "perfectness" in favor of adding more features

Bottom line, you need to have principles but you should also be flexible enough to break those principles when they bring more harm than value.

OwnerDisplayName: BartVG

Title: To be strict or pragmatic?


问:
You're hired to fix a small bug for a security-intensive site. Looking at the code, it's filled with security holes. What do you do?
I've been hired by someone to do some small work on a site. It's a site for a large company. It contains very sensitive data, so security is very important. Upon analyzing the code, I've noticed it's filled with security holes - read, lots of PHP files throwing user get/post input directly into mysql requests and system commands.

The problem is, the person who made the site for him is a programmer with family and children who depend on that job. I can't just say: "your site is a script kiddie amusement park. Let me redo it for you and you'll be fine."

What would you do in this situation?

Update:

I followed some good advice here and politely reported to the developer that I've found some possible security flaws on the site. I pointed out the line and said there could be a possible vulnerability for SQL injection attacks there, and asked if he knew about it. He replied: "sure, but I think that to exploit it the attacker should have information on the structure of the database; I have to understand better".

Update 2:

I said that's not always the case and suggested he follows this Stack Overflow question link in order to deal with it properly: How to prevent SQL injection in PHP? He said he would study it and thanked me for telling him before. I guess my part is done, thanks guys.

答:
In addition to the other answers what you might want to do is point the developer at some resources on how easily SQL injection issues can be exploited, for example sqlmap which is an automated SQL Injection exploitation tool.

What I've found to be effective in demonstrating the seriousness of this kind of issue in the past is showing what can be done with it, so if you run something like that against a dev. copy of the site to show it extracting data etc you might convince them of the seriousness.


问:
TDD - is it just about unit tests?
Do I understand it right that classical TDD is just about unit tests? Don't understand me wrong: I know the difference between TDD and just unit testing. I am asking whether it is correct to use integration test in TDD workflow.

Currently I work on the project where TDD is surely only about unit tests and there is at least one serious problem with it. The majority of our unit tests are behavioural tests which often become false negative (false red) during refactoring (just because some sequence of dependencies calls changed). The project was created in TDD style to make refactoring simple and suddenly refactoring became a hell. Epic fail!

The most obvious decision now is to make our test not unit but integrational (but still with TDD). So if previously we stubbed/mocked class dependencies, now we won't do it (at least not all of them). As result most of our tests will become state (instead of behavioural). And state tests become false negative much more seldom (because they test the result but not the workflow of execution).

So I would like to know how widespread is an approach of using TDD with integration tests. Is it okay? Would be grateful for any resources on this topic. I have read this article but it is a bit... strange

Update. Here I will clarify what I mean under unit test and integration test. Unit test is a test which stubs/mocks all class dependencies. Integration test has real implementations of dependencies (although it can stub/mock some dependencies if needed).

答:
So I would like to know how widespread is an approach of using TDD with integration tests. Is it okay? Would be grateful for any resources on this topic. I have read this article but it is a bit... strange

Acceptance Test Driven Development

The term used for TDD that involves testing the behavior of the system at large rather than a particular unit of code.

I've personally used it to great effect for about 7 years now primarily in web development.

Before you jump in I would caution you against going from one extreme (mocking/stubbing everything outside the unit) to another (not managing external resources at all).  You should assess your needs for development.  Establish what the trade-offs are and choose whichever one yields the greatest value.  Always do the analysis, because "best practices" sometimes are not.

Your Okay, I'm Okay

I wouldn't worry about the practice being "okay".  I think you should focus on if it solves your problem, or at least is a marked improvement.

Title: TDD - is it just about unit tests?


问:
Web Project Class Architecture
I think this is a good question for here but I'm not 100% sure. Please flag if it's too vague.

I've worked on many websites where common framework classes are overridden.

Since I work mostly in .net these days examples would include Page, Masterpage, UserControl, DbContext ect. I believe this could apply to any language though.

Sometimes I can see why it's done, I overrode entity framework's DbContext to include some logging code.

Allot of the time though I don't see why these base classes were created. Because I've inherited most of the sites I can't really ask why.

My question: Is it a good idea/practice when creating a new site to Override the common framework classes mentioned above? Would doing so be considered more of an old style?

答:
It's not a good idea to override framework classes, even when it's supposed to do by authors of the framework. "Always prefer composition over inheritance" - widely known rule.
Overriding code of framework makes your code more dependent and tightly coupled with code of framework.

And just to note: "Masterpage" name looks like "God-object" antipattern case.

Title: Web Project Class Architecture


问:
Is imposing the same code format for all developers a good idea?
We are considering to impose a single standard code format in our project (auto format with save actions in Eclipse). The reason is that currently there is a big difference in the code formats used by several (>10) developers which makes it harder for one developer to work on the code of another developer. The same Java file sometimes uses 3 different formats.

So I believe the advantage is clear (readability => productivity) but would it be a good idea to impose this? And if not, why?

UPDATE

We all use Eclipse and everyone is aware of the plan. There already is a code format used by most but it is not enforced since some prefer to stick to their own code format. Because of the above reasons some would prefer to enforce it.

答:
Yes, that is good to have one code format styles for all developers.

Design the code style formats and import that to all developers eclipse.

This will help when we are merging code to 'Version control' system.


答:
Every professional software developer will prefer to adopt a (good) standard rather than get into evangelical wars over style, for the very reasons you have outlined.

Many software developers wage evangelical wars......

Depending on your position within the team and the team dynamics, you may decide that winning the war is not possible. In this case, it may be best not to start...

Title: Is imposing the same code format for all developers a good idea?

Body:
We are considering to impose a single standard code format in our project (auto format with save actions in Eclipse). The reason is that currently there is a big difference in the code formats used by several (>10) developers which makes it harder for one developer to work on the code of another developer. The same Java file sometimes uses 3 different formats.

So I believe the advantage is clear (readability => productivity) but would it be a good idea to impose this? And if not, why?

UPDATE

We all use Eclipse and everyone is aware of the plan. There already is a code format used by most but it is not enforced since some prefer to stick to their own code format. Because of the above reasons some would prefer to enforce it.


问:
How can architects work with self-organizing Scrum teams?
An organization with a number of agile Scrum teams also has a small group of people appointed as "enterprise architects". The EA group acts as control and gatekeeper for quality and adherence to decisions. This leads to overlaps between the team decision and EA decisions.

For instance, the team might want to use library X or want to use REST instead of SOAP, but the EA does not approve of that.

Now, this can lead to frustration when team decisions are overruled. Taken far enough, it can potentially lead to a situation where the EA people "grabs" all power and the team ends up feeling demotivated and not very agile at all.

The Scrum guides has this to say about it:

Self-organizing: No one (not even the Scrum Master) tells the
  Development Team  how to turn Product Backlog into Increments of
  potentially releasable functionality.

Is that reasonable? Should the EA team be disbanded? Should the teams refuse or simply comply?

答:
A Development Team is made up of 3–9 people with cross-functional skills who do the actual work

Scrum Master should invite "Enterprise Architect" to become a part of the project team. Then the communication between architect and programmers would be excellent.


答:
Question is: What is reason why this Architect team exists? Only reason I can think of is to enforce interoperability between various teams. Or the teams are working on various parts of single product and this architect team exists to keep every part working together.

I really don't think this scheme can work well in agile environment, for exact reasons you say. The various teams should be self-contained and so should be their inputs and outputs. So constraining their outputs should only be as part of requirements on input. But those constraints should be reasonable. Something like "Must not use library X" is not a good requirement, but saying "Must limit number of used 3rd party libraries to minimum" or "Adding new libraries, that aren't used in other teams should be limited." should be fine.

Then I would dissolve the architect team across all teams and use their expertise in questions of architecture. By becoming part of the team, they will be able to better see problems the team is having and might have better ideas or more educated opinions about changing core parts of architecture. It should also be encouraged to architects across teams to communicate to ensure architecture remains consistent across teams.

Title: How can architects work with self-organizing Scrum teams?

Body:
An organization with a number of agile Scrum teams also has a small group of people appointed as "enterprise architects". The EA group acts as control and gatekeeper for quality and adherence to decisions. This leads to overlaps between the team decision and EA decisions.

For instance, the team might want to use library X or want to use REST instead of SOAP, but the EA does not approve of that.

Now, this can lead to frustration when team decisions are overruled. Taken far enough, it can potentially lead to a situation where the EA people "grabs" all power and the team ends up feeling demotivated and not very agile at all.

The Scrum guides has this to say about it:

Self-organizing: No one (not even the Scrum Master) tells the
  Development Team  how to turn Product Backlog into Increments of
  potentially releasable functionality.

Is that reasonable? Should the EA team be disbanded? Should the teams refuse or simply comply?


问:
Is NoSQL a good fit for a graphing app, and how can I compare different NoSql Servers?
I am traditionally a MsSQL or MySQL developer - I have been prototyping a new application that involves storing data from many targets.

I have seen that the app appears to get slow after scaling to 10k targets after inputting around 300k results for each (64 bit ints) - especially once I start trying to average and/or graph a few targets at once.

Once the app is deployed I will need to add around 1k targets a month and store one data point from each for each and every minute for approx 2 years.

I have never used NoSql, but from reading, it sounds like a good fit - create a document for each target and keep adding fields for each target.

So, I was just wondering, is NoSQL the way to go for this project or should I be sticking with traditional SQL - and/or can anyone offer any advice?

And the second part - If NoSQL is a solution can anyone recommend a fair comparison as I am getting lost in biased reviews that seem to say each solution is superior!?

答:
to get the point if either one of the SQL DBs or one kind of NoSQL is right you should first analyze what causes your problem.

is it the amount of data itself,
is it the amount of parallel writes,
is it the amount of parallel reads,
or is it the amount of parallel reads and writes

as far as you have this, you should check how to solve this with SQL, (SQL system are betten then NoSQL systems tells about them)

if you figure out that also a big cluster of SQL with lots of different HD and partitioned data doesn't help then check out depending on your problem which NoSQL systems are there.

as already mentioned there are the graph DBs, they are good for reading and writing lots of connected data. but connections for the data can't be unlimited.

for fast reading there is mongodb, good community and also commercial support.

for fast writing, there is hypertable and hbase . where hypertable is the faster one, but its written in c, and java or php or... apis are only available as thrift libs, which needs a bit more reading how to use it. community is active and responding for both.

mongodb, hypertable and hbase, have all support to create a Map Reduce job.
this is usefull if you want todo stuff on your data which takes longer.

means if you dont need a answer to a query (sql speaking) right now, but during the next hour this is the right approach for you.

but for all NoSQL System, you need to start thinking from scratch, so if you start forgot everything from SQL, and only concentrate on the one NoSQL you wanna use.
and design your data around this system

one thing that most NoSQL have in common is, that data can be stored twice,
on SQL you create foreign keys joins and so.
on NoSQL you simple write the data twice (one step to thinking for such systems), (many system event dont have an update method )


答:
I don't see any conflict here. From what I understand, all the EA (as pompous a title I think that is) is meant to do is QA. Everybody should be aware of that.

You should consider, that in any development methodology (that deserves being considered one) requirements gathering is a crucial step, whether it's iterative or upfront.

Some of these requirements are set by company policy. And these set the ground rules:

The team will have to abide by them as by any other requirement. Challenging the policy is then simply outside the scope of the project and should be handled separately.

The EA's job is to enforce these requirements and not impose their personal fancy. They don't like X then that's their personal opinion. Nothing more, nothing less. Treat it like any other opinion. However, if the EA can show that using X violates an existing requirement, then they are well within their right to forbid the use of X and if they know a workable alternative and the team doesn't, then it's their right to enforce it.

But either way, a requirement is either met or not. If that determination is hard to make, then the requirement is lacking and you need to reiterate it to become truly testable (in a broader sense). You should handle that as any requirement reiteration.


问:
Codeigniter/MVC workflow
Bit of a workflow question.

I'm just staring with MVC and wondered how other people usually work in MVC? The 2 options I see is to code the model and controller completely first and then work on the views after. The other option is to code all parts at the same time.

I'm looking for what might be the quickest most efficient way to code in MVC? We don't have inhouse designers or designated jobs so everyone does the same tasks (coding, designing, testing, db, etc).

Thanks!

答:
There's a third option, start by writing your tests. It's the better option, and it's not specific to MVC. If you do start by writing tests, then the next step depends on your approach to MVC:

Fat controllers / skinny models

Your controllers do all the heavy lifting, while your models are essentially POPOs, tasked with maintaining state between requests.

Skinny controllers / fat models

Your controllers are limited to passing stuff around, most (if not all) of your business logic lives in your models.

CodeIgniter favours the first approach but it doesn't restrict you from the latter one. It's completely up to you which one you'll follow, personally I'd strongly suggest the second approach, simply because with fat models you'll get the chance to test your business logic very early in the development cycle.

With skinny models, you'll have to build both your controllers and your models before you'll be able to test your business logic, and that's not particularly efficient. Your business logic is the more important part of your application, I think it's obvious that the sooner you build and test it, the better.

To summarize, my workflow is:

Write the business logic tests,

Write the models that would satisfy those tests,

Pretend I practice TDD for everything else,

Write the controllers and views.

Further reading:

The M in MVC: Why Models are Misunderstood and Unappreciated

Building a Domain Model – An Introduction to Persistence Agnosticism

Preventing Code Rot 101: Unit Testing

Title: Codeigniter/MVC workflow


问:
Whats the greatest most impressive programing feat you ever witnessed?
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?

答:
8 bits video game programmer on computer from the 80's (ie: Commodore 64),
some pretty good game were in machine language, and their size were often smaller than a bitmap for a Windows icon ;-) Optimization at it's finest

Geos (a WYSIWYG OS for Commdore 64) was very impressive for it's time

ContentLicense: CC BY-SA 2.5


答:
If you're going to stick to the same IDE and incorporate some formating tools, it's a good idea because you're not requiring too much effort. Keep the rules simple with a focus on readability and not anal retentiveness. That should be the measuring stick.

Although a consistently formated ball of mud is better than just a ball of mud, your time would be better spent cleaing it up instead of getting too picky about where the brackets go. Don't turn into the pin-headed manager who feels like they're doing their job by counting indent spaces during a code review along with making sure the new cover sheets are on the TPS Reports.

Personal preferences are just that and rarely improve production: https://stackoverflow.com/questions/249432/whats-the-reasoning-behind-the-different-brace-forms

If it does, get over it and get something done.


答:
This sort of thing is necessary to maintain balance between needing a large team to get the project done, and the need to keep agile teams small.

Generally, the 'team lead scrum' is composed of one member elected from each of the smaller teams. That provides some of the self-organizing nature, as well as providing some manner of representation so that decisions made by the high level group are accepted by the agile group.

For your particular scenario, something should be done to stop the agile team demotivation, but probably not rebellion or simple acceptance. The team needs to realize that you're there to make good software, not kowtow to ideals. Having a bunch of different teams each using different technologies to do similar things in the same project is going to lead to worse software. Having a bunch of different teams use different coding standards in the same project is going to lead to worse software.

So you're going to need some way to come to some consensus about how the project is going to work. The team lead scrum is used in other places effectively. You might need to do something differently, or look into why your group is not doing it effectively.


答:
What are you trying to gain, how anal retentive are you going to be in enforcing it (and in the level of detail your "rules" will be set out), are you going to try to enforce it on code written in different languages, are you going to try to enforce it retroactively on existing code?

a common look and feel to code can indeed help make code more readable, but also can make things worse if it's the wrong look and feel. _hUngarian_lpfstr notation being a prime example :)

I've seen "code standards" enforcing the number of spaces of whitespace between in comment blocks, the alphabetical ordering of method names, and other nonsense. Don't do that.

Different languages have different standards people are used to who're experienced in their use. Some even mandate these standards (think Python, Cobol, Visual Studio automatically imposes C++ style bracing conventions while Java uses C style by convention, etc. etc.).

never change existing code for the sake of changing it, you're only introducing new problems that way. And that means code sections as well as entire source files. So don't go around reformatting existing code when someone changes a single line in a 1000 line file.

experienced programmers can be much more productive if they don't have to think half the time whether what they're writing will "look right" to the automatic approval system, or the reviewer. They're also going to be in the habit of writing clean code simply because that's what works, even if there are small differences between their natural styles.

So while there are good reasons to impose a specific style and standard, there's as good reasons to not do so (too) strictly.


答:
Yes, consistency is a good idea, for reasons others have mentioned.

I just wanted to add a couple of points which haven't been used elsewhere:

Oracle has published a set of conventions for Java, which are the de facto standard.

Using these should help you avoid arguments about which style to follow.

A lot of public libraries and open source projects tend to use these conventions, so when you need to look at those the formatting should be familiar.

The Eclipse formatter has built-in rules to match these conventions, which should also help.

You might want to consider building a hook into your source control setup so that code gets auto-formatted before it gets into the main branch.

You can avoid battles with particularly stubborn programmers who refuse to follow the standard. They can even use their own formatting while they work, which will get standardized later!

If you end up using custom formatting settings (e.g. a lot of people ignore the "max 80 chars per line" convention) you only have to make changes in one place.


问:
How to selectively update properties of an object on the server
I have a GWT website that displays some data onto the client in a tabular form. Some of the fields are editable, when any change is made the save button becomes active.

There are multiple properties that may have changed, how would I go about updating them on the server? Additionally I'd like to provide an undo button so that the changes are reverted.

What I'm thinking of right now is to use the setters and check if the current value is the same as the changed value if there is a change then a request to a process in the background will be fired.

But I'm not sure this is the best approach and maybe setters with extra logic aren't the best practice. I think this is a problem that many web applications have to deal with and maybe there is a pattern that makes all of this more elegant.

It would be nice if someone could explain how they would solve this.

答:
This strikes me as a borderline-SO question, but I'll answer here. I think you want to use the Command Pattern. Implementing that pattern gives you the structure required to support undo and even multi-level undo.

The easiest approach would be to have each "Save" press generate a Command object with the form's current values; when your processing code receives the command it can first "archive" the data object's current state to the command so that you can have a before/after picture of the data object and thereby support undo.

That approach is slightly hamfisted and could be improved by only recording the information of the properties that are actually changing. I'll leave it up to you to decide if it's worth adding that extra logic to essentially "diff" the field values, as it definitely adds an extra layer of bookkeeping.

I also suggest further reading in the somewhat-related Command-Query Separation principle. It's a very useful principle to follow in many areas of architecture.


答:
The choice of technology used is part of the requirements of the software, which means it's part of the feature request that you don't use certain technologies, for whatever reason.

The architects speak for the systems and the codebase because the systems and the codebase can't speak for themselves. Having an architect is generally in the long-term best interests of a company, especially one which relies on software that is built in-house.

The architects aren't telling the developers how to turn the backlog into increments (sprints), they're saying which technologies can and can't be used. You're conflating two different issues.

The solution is to change nothing. If your teams are getting frustrated because the architects are too restrictive or too overbearing, that's a personnel issue that has nothing to do with SCRUM and should be taken up with the business stakeholders as an issue of employee satisfaction and, if possible, the bottom line ( "It takes us x% longer to develop features for y because architect z wont let us use Turbo Pascal." )


答:
The group over at Scaled Agile Framework speak to this really well.  Most of us deal at the Team Level, but when scaling up we need to recognize that there are roles to play at the Program and Portfolio level as well.  Architectural decisions need to be made across the organization, and that should feed into what is happening at the lower levels of the organization.  There's nothing wrong with having architectural decisions!

Related to this, Dean Leffingwell's recent book on Agile Software Requirements is a good read on this topic, I've been reading it myself.


答:
I strongly recommend that humans enforce code formatting, and that minor infractions are graciously overlooked or touched-up. Reasons for this are, briefly,

The machine gets it wrong at the worst possible time, and usually when you are using a new language feature. How will it handle closures in Java, etc? Jalopy has trouble with enums with member functions.

I think it's a very reasonable burden to put on the programmer to please produce code for the company that looks like company code. I've found it helpful to mention that this is how code is formatted "here," not how all code should be formatted everywhere. Their previous company may have chosen a different path, and that's OK. Not unlike vernacular language, there are idioms specific to your code culture that you want to bring out.

Enforcement of code syntax is best done with code reviews:

If formatting is important, than it draws your organization to do code reviews. This is of huge benefit.

If a formatting rule is broken, a human can look at it and judge better than a machine if the intent is conveyed more cleanly. This is very rare, but happens occasionally.

Regarding "readability => productivity", code structure (such as single-responsibility classes and functions) will buy you far more faster than code formatting. Code formatting can be a help, but different minds parse statements differently -- not everyone will be "more productive." I would like to double-down on code structure over formatting because that is something that will also pull you into doing code reviews and get the team into thinking about how the program works, not how a single loop looks.

I'm not a big fan of Domain Driven Design, but it is one recent model that has a VERY well defined idea as to how code should be structured and code formatting conventions flow naturally out of a Domain Driven Design structured program. Again... I don't like DDD, but it's a great example because it's so well defined.

I suppose the theme of this answer is, Do code reviews and let formatting flow from the culture and out of the review process.


答:
I was on a team that used the Checkstyle plugin. Rather than use the out-of-the-box features, we formed a small committee of interested developers. We debated over what seemed missing, what seemed excessive, and hammered things out. We all learned something in the process, and strengthened those developer muscles.

(Examples of our decisions: 72 characters wide is too small, but 120 was better; it's better to use _ALLCAPS for static finals; enforcing single-exit from a function is a good idea.)

When we had code reviews, one of the first questions was: "Have you run it through Checkstyle?" Complying with the coding standards was largely automated, and it drew the attention away from the reviewer being picky. It was wonderfully easy to have Checkstyle highlight a method signature, right-click, and change a variable to final. It could also fix the indentations and braces so that everyone's code had a similar look and feel. Missing a Javadoc for a public function? Checkstyle will flag the function.

(Removing code smell is more important than consistent formatting. This is a benefit of automated tools.)

I would place automated tools like Checkstyle less as imposing the same format and more on encouraging a similar look and feel. And when you're herding cats, an automated tool can help sharpen skills and reduce code smell without bruising fragile egos.


答:
Waterfall or Scrum (this seems like mixing two, which yes, is not going to work), that sounds like a pretty pointless layer of management to me in the first place. Gatekeepers on technology decisions should be lead devs, the overall manager of development whose job should be to keep dev preferences from turning your app into a hydra of tech choices, and whoever's budget has to foot the potential bill.

Nothing continues to dumbfound me like non-devs actually having the gall to make technology decisions without even consulting the actual people who have to suffer the consequences of those decisions.


问:
What are some JavaScript selectors?
I was at an interview recently and although they knew that I was a beginner in javascript they asked me what selectors I used before? I didn't know what to say. </p>

<p>I came back home and searched for it but can't find a clear definition.  Isn't a selector something like a .class or #id? </p>

答:
Yes, you were interviewed by morons. Consider that bullet dodged. They were probably thinking of jQuery, which you probably should learn, but it does in fact use CSS selectors and xpath... (whatever you call xpath statements/selector thingies) for syntax. The right answer if you should want to be hired by somebody who makes the same mistake again is "JavaScript doesn't have selectors. Are you talking about jQuery? Or are you referring to the DOM API?" The DOM API, btw, is something you should already know if you don't.

Edit: Okay, maybe not total morons. They could have been thinking of the query selector API (see Dystroy's answer) but IMO, that still should have been clear.

Title: What are some JavaScript selectors?


答:
Your interviewer was probably referring to the query language which lets you form selectors to find elements in the DOM using methods like querySelectorAll.

Note that selectors are normalized by the w3.org in the selectors API :

Selectors, which are widely used in CSS, are patterns that match
  against elements in a tree structure [SELECT][CSS21]. The Selectors
  API specification defines methods for retrieving Element nodes from
  the DOM by matching against a group of selectors. It is often
  desirable to perform DOM operations on a specific set of elements in a
  document. These methods simplify the process of acquiring specific
  elements, especially compared with the more verbose techniques defined
  and used in the past.

The purpose of the question could be to check you know those selectors exist, which would make a difference with many developers only aware of the use of libraries like jQuery and who would make the mistake of answering that JavaScript doesn't have selectors.

Title: What are some JavaScript selectors?

Body:
I was at an interview recently and although they knew that I was a beginner in javascript they asked me what selectors I used before? I didn't know what to say. </p>

<p>I came back home and searched for it but can't find a clear definition.  Isn't a selector something like a .class or #id? </p>


答:
I currently work at a place where a standard code format is enforced and the code is automatically formatted when saving the file, just like you are about to do. As a new member of the company I found that the common formatting rules gave me a warm and fuzzy feeling that "these guys know what they are doing", so I couldn't be happier. ;) As a related side note, with the common formatting rules we also enforce certain, rather strict compiler warning settings in Eclipse, with most of them set to Error, many set to Warning, and almost none set to Ignore.

I'd say there are two main reasons to enforce a single code format in a project. First has to do with version control: with everybody formatting the code identically, all changes in the files are guaranteed to be meaningful. No more just adding or removing a space here or there, let alone reformatting an entire file as a "side effect" of actually changing just a line or two.

The second reason is that it kind of takes the programmers' egos out of the equation. With everybody formatting their code the same way, you can no longer as easily tell who has written what. The code becomes more anonymous and common property, so nobody needs to feel uneasy about changing "somebody else's" code.

Those being the main reasons, there are others as well. I find it comforting that I don't have to bother myself with thinking about the code formatting, as Eclipse will do it for me automatically when I save. It's care-free, like writing documents with LaTeX: it's formatted afterwards and you don't have to worry about it while writing. I have also worked in projects where everybody has had their own styles. Then you have to think about stupid and meaningless issues such as if it's OK to modify somebody else's code in your own style, or if you should try to imitate their style instead.

The only argument against common code formatting settings that I can think of for your case is that it's apparently an already ongoing project, so it will cause lots of unnecessary changes in all the files, messing up the actual file histories. The best case scenario is if you can start enforcing the settings right from the beginning of a project.


问:
Should I test inherited methods?
Suppose I have a class Manager derived from a base class Employee, and that Employee has a method getEmail() that is inherited by Manager.  Should I test that the behaviour of a manager's getEmail() method is in fact the same as an employee's?

At the time these tests are written the behaviour will be the same, but of
course at some point in the future someone might override this method, change its behaviour, and therefore break my application.  However it seems a bit strange to essentially test for the absence of meddling code.

(Note that testing Manager::getEmail() method does not improve code coverage (or indeed any other code quality metrics (?)) until Manager::getEmail() is created/overridden.)

(If the answer is "Yes", some information about how to go about managing tests that are shared between base and derived classes would be useful.)

An equivalent formulation of the question:

If a derived class inherits a method from a base class, how do you express (test) whether you're expecting the inherited method to:

Behave in exactly the same way as the base does right now (if the behaviour of the base changes, the behaviour of the derived method doesn't);

Behave exactly the same way as the base for all time (if the behaviour of the base class changes, the behaviour of the derived class changes as well); or

Behave however it wants to (you don't care about the behaviour of this method because you never call it).

答:
Should I test that the behaviour of a manager's getEmail() method is
  in fact the same as an employee's?

I would say no as it would be a repeated test in my opinion I would test once in the Employee tests and that would be it.

At the time these tests are written the behaviour will be the same,
  but of course at some point in the future someone might override this
  method, change its behaviour

If the method is overridden then you would need new tests to check the overridden behaviour. That is the job of the person implementing the overriding getEmail() method.

Title: Should I test inherited methods?


答:
I'd take the pragmatic approach here: If someone, in the future, overrides Manager::getMail, then it is that developer's responsibility to provide test code for the new method.

Of course that's only valid if Manager::getEmail really has the same code path as Employee::getEmail! Even if the method is not overridden, it might behave differently:

Employee::getEmail could call some protected virtual getInternalEmail which is overridden in Manager.

Employee::getEmail could access some internal state (e.g. some field _email), which can differ in the two implementations: For example, the default implementation of Employee could ensure that _email is always firstname.lastname@example.com, but Manager is more flexible in assigning mail addresses.

In such cases, it is possible that a bug manifests itself only in Manager::getEmail, even though the implementaion of the method itself is the same. In that case testing Manager::getEmail separately could make sense.

Title: Should I test inherited methods?

Body:
Suppose I have a class Manager derived from a base class Employee, and that Employee has a method getEmail() that is inherited by Manager.  Should I test that the behaviour of a manager's getEmail() method is in fact the same as an employee's?

At the time these tests are written the behaviour will be the same, but of
course at some point in the future someone might override this method, change its behaviour, and therefore break my application.  However it seems a bit strange to essentially test for the absence of meddling code.

(Note that testing Manager::getEmail() method does not improve code coverage (or indeed any other code quality metrics (?)) until Manager::getEmail() is created/overridden.)

(If the answer is "Yes", some information about how to go about managing tests that are shared between base and derived classes would be useful.)

An equivalent formulation of the question:

If a derived class inherits a method from a base class, how do you express (test) whether you're expecting the inherited method to:

Behave in exactly the same way as the base does right now (if the behaviour of the base changes, the behaviour of the derived method doesn't);

Behave exactly the same way as the base for all time (if the behaviour of the base class changes, the behaviour of the derived class changes as well); or

Behave however it wants to (you don't care about the behaviour of this method because you never call it).


问:
Plugin Architecture: How to Handle Databases and Logging?
I am in the process of designing an architecture for a plugin based application and I have some questions about how to handle database access and logging. The goal of my application is to allow a device my company is manufacturing to send messages over any number of third-party protocols and to any number of third party devices. Because of the nature of my application, I need to log every message that is sent via my system in reasonable detail.

Here's what I am thinking on the Database side: There will be a global message table which stores all of the implementation agnostic data we have, and then there will be a table (or set of tables) for each messaging plugin as defined by the plugin writer which references the Global Message table via a foreign key.

It is handling these other tables that I am having a hard time figuring out how to design safely. On the one hand, I don't particularly want to give the plugins full access to the database (I want them to have the fewest possible privileges), on the other hand I want the plugin developers to have full reign to log any data they need to tables that they define similarly to how plugins work in Wordpress. Additionally, I don't want logging to the Database to be optional at all: Good logging is crucial to my application.

Things I have considered:

Designing a logging infrastructure which allows a plugin to define (maybe in an XML file) the tables it needs in the DB and a mapping between those tables and objects that they will return, and using those mappings and table definitions to write to the DB the results from method calls.

Making a naming convention for Stored Procedures in the DB that each plugin must define when defining their tables and automatically calling those stored procedures after sending a message.

Allowing each plugin to implement a logging method which returns a String holding the proper SQL query.

Each of the above solutions makes me a little uncomfortable, but I'm not sure what other approaches might exist. Any Suggestions?

Implementation Details:
I am writing my application in Java, and I am using a hand-rolled plugin solution, so I have a pretty decent amount of flexibility. Since none of the actual code has been written (other than some proof-of concept code which is really just for reference), I can make fairly major changes to my plan without great cost.

答:
How are you planning to implement the "sending" of the messages ? There are different approaches based on this answer. For example, are you whipping up your custom implementation of Apache James Server ?
You haven't mentioned if you are working on any available frameworks. But I think one other approach you can consider is to use AOP for this. You can weave your aspects around each sender function and whenever such a function is called logging statements can be prepared and documented in a db.</p>


答:
I would.

If you're thinking "well, it's really only calling Employee::getEmail() because I don't override it, so I don't need to test Manager::getEmail()" then you're not really testing the behavior of Manager::getEmail().

I would think of what only Manager::getEmail() should do, not whether or not it's inherited or overridden.  If the behavior of Manager::getEmail() should be to return whatever Employee::getMail() returns, then that's the test. If the behavior is to return "pink@unicorns.com", then that's the test. It doesn't matter whether it's implemented by inheritance or overridden.

What does matter is that, if it changes in the future, your test catches it and you know something either got broken or needs to be reconsidered.

Some people may disagree with the seeming redundancy in the check, but my counter to that would be you're testing the behavior Employee::getMail() and Manager::getMail() as distinct methods, whether or not they're inherited or overridden. If a future developer needs to change the behavior of Manager::getMail() then they need to also update the tests.

Opinions may vary though, I think Digger and Heinzi gave reasonable justifications for the opposite.

Title: Should I test inherited methods?


答:
We also have multiple, agile teams (some do Kanban, some Scrum), and architects. The architects are responsible for infrastructure that spans all of our products (helper libraries, authentication, build infrastructure) etc. They make technical decisions, but also implement things, mostly infrastructure components.

This works well, and there's usually no conflict. I believe one crucial point is:

The architects have no formal authority over the teams, and cannot just overrule them. Normally, the architects make decisions that apply to all products, and the teams make decisions for their product. If there is a conflict, then architect & team just need to reach an agreement, or escalate to management (though that rarely happens).

I think it's really important to make architects and developers peers. Both work towards a common goal, just in different areas. If no one can just "overrule" the other, cooperation will be better.


答:
What is the purpose of the messages? It sounds like they can be schema-less/unstructured.  Hard-coding the implementation to the application database is probably going to come back to haunt you. If the logging is unstructured anyway, why not just do like/use log4j or similar?
One option is to just write a thin wrapper API around log4j.  Presumably you want to maintain logging context such that you can retrieve all logs from all plugins related to a single action/user.  If so, then you need a way to tie the different logs together.

AppLogger.logMessage(AppContext context, PluginContext plugin, string log)

your storage is abstracted from the plugins, who shouldn't really care where the data is logged.  This allows you to easily move it to FS, Queues, separate DB, etc without the plugins knowing/caring.

If you want to keep logging in the main DB, just store the logs in the master table with the log message stored as string/blob/xml/json, whatever the DB supports easily.

Title: Plugin Architecture: How to Handle Databases and Logging?

Body:
I am in the process of designing an architecture for a plugin based application and I have some questions about how to handle database access and logging. The goal of my application is to allow a device my company is manufacturing to send messages over any number of third-party protocols and to any number of third party devices. Because of the nature of my application, I need to log every message that is sent via my system in reasonable detail.

Here's what I am thinking on the Database side: There will be a global message table which stores all of the implementation agnostic data we have, and then there will be a table (or set of tables) for each messaging plugin as defined by the plugin writer which references the Global Message table via a foreign key.

It is handling these other tables that I am having a hard time figuring out how to design safely. On the one hand, I don't particularly want to give the plugins full access to the database (I want them to have the fewest possible privileges), on the other hand I want the plugin developers to have full reign to log any data they need to tables that they define similarly to how plugins work in Wordpress. Additionally, I don't want logging to the Database to be optional at all: Good logging is crucial to my application.

Things I have considered:

Designing a logging infrastructure which allows a plugin to define (maybe in an XML file) the tables it needs in the DB and a mapping between those tables and objects that they will return, and using those mappings and table definitions to write to the DB the results from method calls.

Making a naming convention for Stored Procedures in the DB that each plugin must define when defining their tables and automatically calling those stored procedures after sending a message.

Allowing each plugin to implement a logging method which returns a String holding the proper SQL query.

Each of the above solutions makes me a little uncomfortable, but I'm not sure what other approaches might exist. Any Suggestions?

Implementation Details:
I am writing my application in Java, and I am using a hand-rolled plugin solution, so I have a pretty decent amount of flexibility. Since none of the actual code has been written (other than some proof-of concept code which is really just for reference), I can make fairly major changes to my plan without great cost.


答: Why does it have to be a database?  Why not just have a generic "data sink" and write streams of data to it.  Plugins are responsible for serializing and deserializing their own data, and you provide a simple read/write facility.  They give you a reference to a message stream, then you write it and hand them back a GUID (or some other token) to identify the data.</p>


答:
Anders Hejlsberg: the Turbo Pascal language and the compiler. I still think after all these years TPC is a masterpiece of software engineering. It is the most compact and the fastest native-code (starting from certain versions also optimizing) compiler I've ever seen. In the Borland Pascal IDE there was no "compilation" essentially. You modified your code, hit F9 and watched your program running straight away, and that was on a 8MHz or 12MHz machine. TPC had later evolved into Delphi, then Hejlsberg joined Microsoft and co-authored C#.

I'd love to take a look at the sources of earlier TPC versions, but unfortunately despite numerous requests Borland never opened them.

Hejlsberg's compiler was inspired by this book: Niklaus Wirth, Algorithms + Data Structures = Programs

Title: Whats the greatest most impressive programing feat you ever witnessed?

Body:
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?


问:
.NET Properties - Use Private Set or ReadOnly Property?
In what situation should I use a Private Set on a property versus making it a ReadOnly property?  Take into consideration the two very simplistic examples below.

First example:

```<code>Public Class Person

    Private _name As String

    Public Property Name As String
        Get
            Return _name
        End Get
        Private Set(ByVal value As String)
            _name = value
        End Set
    End Property

    Public Sub WorkOnName()

        Dim txtInfo As TextInfo = _
            Threading.Thread.CurrentThread.CurrentCulture.TextInfo

        Me.Name = txtInfo.ToTitleCase(Me.Name)

    End Sub

End Class

// ----------

public class Person
{
    private string _name;
    public string Name
    {
        get { return _name; }
        private set { _name = value; }
    }

    public void WorkOnName()
    {
        TextInfo txtInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
        this.Name = txtInfo.ToTitleCase(this.Name);
    }
}
</code>```

Second example:

```<code>Public Class AnotherPerson

    Private _name As String

    Public ReadOnly Property Name As String
        Get
            Return _name
        End Get
    End Property

    Public Sub WorkOnName()

        Dim txtInfo As TextInfo = _
            Threading.Thread.CurrentThread.CurrentCulture.TextInfo

        _name = txtInfo.ToTitleCase(_name)

    End Sub

End Class

// ---------------

public class AnotherPerson
{
    private string _name;
    public string Name
    {
        get { return _name; }
    }

    public void WorkOnName()
    {
        TextInfo txtInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
        _name = txtInfo.ToTitleCase(_name);
    }
}
</code>```

They both yield the same results.  Is this a situation where there's no right and wrong, and it's just a matter of preference?

答:
Use private set when you want setter can't be accessed from outside.

Use readonly when you want to set the property only once. In the constructor or variable initializer.

TEST THIS:

```<code>void Main()
{
    Configuration config = new Configuration();
    config.ResetConfiguration();

    ConfigurationReadOnly configRO = new ConfigurationReadOnly();
    configRO.ResetConfiguration();
}

public class Configuration
{
    public Color BackgroundColor { get; private set; }
    public Color ForegroundColor { get; private set; }
    public String Text { get; private set; }

    public Configuration()
    {
        BackgroundColor = Color.Black;
        ForegroundColor = Color.White;
        Text = String.Empty;
    }

    public void ResetConfiguration()
    {
        BackgroundColor = Color.Black;
        ForegroundColor = Color.White;
        Text = String.Empty;
    }
}

public class ConfigurationReadOnly
{
    public readonly Color BackgroundColor;
    public readonly Color ForegroundColor;
    public readonly String Text;

    public ConfigurationReadOnly()
    {
        BackgroundColor = Color.Black;
        ForegroundColor = Color.White;
        Text = String.Empty;
    }

    public void ResetConfiguration()
    {
        BackgroundColor = Color.Black; // compile error: due to readonly keyword
        ForegroundColor = Color.White; // compile error: due to readonly keyword
        Text = String.Empty; // compile error: due to readonly keyword
    }
}
</code>```

Body:
Use private set when you want setter can't be accessed from outside.

Use readonly when you want to set the property only once. In the constructor or variable initializer.

TEST THIS:

void Main()
{
    Configuration config = new Configuration();
    config.ResetConfiguration();

    ConfigurationReadOnly configRO = new ConfigurationReadOnly();
    configRO.ResetConfiguration();
}

public class Configuration
{
    public Color BackgroundColor { get; private set; }
    public Color ForegroundColor { get; private set; }
    public String Text { get; private set; }

    public Configuration()
    {
        BackgroundColor = Color.Black;
        ForegroundColor = Color.White;
        Text = String.Empty;
    }

    public void ResetConfiguration()
    {
        BackgroundColor = Color.Black;
        ForegroundColor = Color.White;
        Text = String.Empty;
    }
}

public class ConfigurationReadOnly
{
    public readonly Color BackgroundColor;
    public readonly Color ForegroundColor;
    public readonly String Text;

    public ConfigurationReadOnly()
    {
        BackgroundColor = Color.Black;
        ForegroundColor = Color.White;
        Text = String.Empty;
    }

    public void ResetConfiguration()
    {
        BackgroundColor = Color.Black; // compile error: due to readonly keyword
        ForegroundColor = Color.White; // compile error: due to readonly keyword
        Text = String.Empty; // compile error: due to readonly keyword
    }
}


问:
Good design for delegates in a service oriented architecture
My problem is quite complex to explain and my English is not excellent, so I hope you can understand my question.

In a service oriented architecture there are some modules that own data used by all the others applications end these modules expose the data via Remote Method Invocation and Web Services.

We the developers of the module have seen that the code that invokes these modules is repeated in all the other modules, so we decided to put in common the code and created a new module named Common Delegates. The responsabilities of this new module are:

keep informations about the hostname, port and JNDI and/or web service names;

instantiate and use the service locator;

instantiate and call the stubs to the remote modules.

But the methods exposed by the Common Delegates modules use the same Request and Response classes that are defined in the called modules. This means that this module does not act as a layer of decoupling.

In some cases this module created problems of circular dependencies during maven builds.

Is it a good thing to split the Common Delegates module into many different Maven artifacts to avoid circular dependencies, one for the called module? For example if I need to call via RMI the module A, I will have to use the Module A delegate.

Is it a good thing to make this delegates to be also a decoupling layer, meaning that they will expose their own Request and Response beans and transform them into the beans used by the called methods?

答:
so your problem is that the services will call each other, if i assume, that the services itself have no circular dependency, then you need to create 2 delegates for each service,
one is a delegate to register the service,
the other is a delegate to lookup a service.

where each delegate will extend an abstract delegate which holds the logic to register or lookup a service.
and you need to separate your interface into an own jar.

then you have:

```<code>interface UserService{}

interface EmailService{}

class UserServiceImpl implements UserService{
 }

class EmailServiceImpl implements EmailService{
 use UserServiceLookup
 }

class abstract BindDelegate{}

class abstract LookupDelegate{}

class UserServinceBindDel extends BindDelegate{
 use UserServiceImpl
 }

class EmailServiceBindDel extends BindDelegate{
use EmailServiceImpl
 }

class UserServiceLookup extends LookupDelegate{
 use UserService
 }

class EmailServiceLookup extends LookupDelegate{
   use EmailService
 }
</code>```

in this case i also would rename  BindDelegate just to Binder, and LookupDelegate just to Resolver or Lookup

but a better way would be to avoid this delegation, because as you see there is lots of code, so now you save some lines of code for resolving and binding, but you need to write always 2 new classes.

in such case that you need RMI, i would go for a generator.
the generator will parse your code, a config while or something else, and out of this information he will generate the server, stubs and skeletons classes.

so you just need to write the generator once, and thats all.
the duplication of code is done by generator. if you need to change it, just change the generator, run it and you have you changed code for all services.

if you dont want to write the generator by your self have a look at this

http://www.distributeme.org

there is a ready open source generator with lots of additional stuff for RMI and remote services.

if RMI is not needed, you can switch to REST Services as example, with REST, you can create one single delegator which will be able to call all other services, without having a circular dependency because he just makes a http call to another url, with another json string, the services are loose coupling.

Body:
so your problem is that the services will call each other, if i assume, that the services itself have no circular dependency, then you need to create 2 delegates for each service,
one is a delegate to register the service,
the other is a delegate to lookup a service.

where each delegate will extend an abstract delegate which holds the logic to register or lookup a service.
and you need to separate your interface into an own jar.

then you have:

interface UserService{}

interface EmailService{}

class UserServiceImpl implements UserService{
 }

class EmailServiceImpl implements EmailService{
 use UserServiceLookup
 }

class abstract BindDelegate{}

class abstract LookupDelegate{}

class UserServinceBindDel extends BindDelegate{
 use UserServiceImpl
 }

class EmailServiceBindDel extends BindDelegate{
use EmailServiceImpl
 }

class UserServiceLookup extends LookupDelegate{
 use UserService
 }

class EmailServiceLookup extends LookupDelegate{
   use EmailService
 }

in this case i also would rename  BindDelegate just to Binder, and LookupDelegate just to Resolver or Lookup

but a better way would be to avoid this delegation, because as you see there is lots of code, so now you save some lines of code for resolving and binding, but you need to write always 2 new classes.

in such case that you need RMI, i would go for a generator.
the generator will parse your code, a config while or something else, and out of this information he will generate the server, stubs and skeletons classes.

so you just need to write the generator once, and thats all.
the duplication of code is done by generator. if you need to change it, just change the generator, run it and you have you changed code for all services.

if you dont want to write the generator by your self have a look at this

http://www.distributeme.org

there is a ready open source generator with lots of additional stuff for RMI and remote services.

if RMI is not needed, you can switch to REST Services as example, with REST, you can create one single delegator which will be able to call all other services, without having a circular dependency because he just makes a http call to another url, with another json string, the services are loose coupling.


问:
How to run an applet like a desktop application without installing entire JDK?
I want to make a desktop application- an analog-clock with the option of setting alarms using java. For rendering all the graphics and the button features, a Swing applet is the answer.

But the problem is that I want to run the applet onto the desktop and so need an applet viewer like thing. Applet viewer comes with the JDK and I think installing entire JDK on a system for running just a simple alarm clock is really not a good idea at all because it will take a lot of space.

Is there a way out? Can I get just the applet viewer (or anything similar to that) instead of entire JDK so that I can run my applet?  Or is there any other way I can do my project using Java?

答:
For applet to run without JDK ie not through appletviewer you can follow these steps -

Embed it in HTML using applet tag -

```
applet ARCHIVE="jar file or external jar files if any" code ="class name with .class extn" width = 800 height =500>
```

Create jar file for your code.

Sign all your jar files using jarsigner

Run your HTML file with JRE installed for browsers

you can view your applet in browser with this anywhere.

Body:
For applet to run without JDK ie not through appletviewer you can follow these steps -

Embed it in HTML using applet tag -

applet ARCHIVE="jar file or external jar files if any" code ="class name with .class extn" width = 800 height =500>

Create jar file for your code.

Sign all your jar files using jarsigner

Run your HTML file with JRE installed for browsers

you can view your applet in browser with this anywhere.


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答: Ted Felix's Qbasic Tutorial encouraged me to learn to program with basic. From there I was so motivated that I went on to try to learn other languages. It is a very inspiring tutorial for beginning programming.</p>


问:
Which of these OOP examples demonstrate proper OOP concepts?
I'm still trying to wrap my head around OOP. All of the following examples work, of course, but is there one (or possibly another) that best exemplifies OOP concepts?

```<code>/**
 * For the following examples the Image class queries an image
 * and associated info from a database, which is passed on
 * instantiation via dependency injection.
 */

$image = new Image(new Db());
</code>```

Example 1:

```<code>if ($image->setImageId($id, $size)) {
    header('content-type: ' . $image->content_type);
    header('content-length: ' . $image->length);
    echo $image->getBytes();
}
</code>```

Example 2:

```<code>if ($image_info = $image->getImageInfoByIdAndSize($id, $size)) {
    header('content-type: ' . $image_info->content_type);
    header('content-length: ' . $image_info->length);
    echo $image->getImageBytesByIdAndSize($id, $size);
}
</code>```

Example 3:

```<code>$image->setImageIdAndSize($id, $size);

if ($image_info = $image->getImageInfo()) {
    header('content-type: ' . $image_info->content_type);
    header('content-length: ' . $image_info->length);
    echo $image->getImageBytes();
}
</code>```

答:
I agree with delnan's comment about "OOP", and that there's really no such thing as "proper OOP concepts", but in terms of general coding principles, I think example 2 is a clear winner compared to the others.

Examples 1 & 3 are the same thing with different names.  In this case it's not obvious at all that setting the object's ID and size would cause a database fetch and its other properties to be populated. I've debugged code like this and it's hard to track down exactly what's happening with these kinds of side effects hidden all over the place.

Example 2 is a sort of combination of a Data Access Object and a Factory, and these could potentially be separated out, but either way it's more obvious to the reader what is happening.

Edit
Here's an even clearer representation:

```<code>if ($image = $image_data_access->getImageById($id)) {
    $image->scaleTo($size);
    header('content-type: ' . $image->content_type);
    header('content-length: ' . $image->length);
    echo $image->getBytes();
}
</code>```

Body:
I agree with delnan's comment about "OOP", and that there's really no such thing as "proper OOP concepts", but in terms of general coding principles, I think example 2 is a clear winner compared to the others.

Examples 1 & 3 are the same thing with different names.  In this case it's not obvious at all that setting the object's ID and size would cause a database fetch and its other properties to be populated. I've debugged code like this and it's hard to track down exactly what's happening with these kinds of side effects hidden all over the place.

Example 2 is a sort of combination of a Data Access Object and a Factory, and these could potentially be separated out, but either way it's more obvious to the reader what is happening.

Edit
Here's an even clearer representation:

if ($image = $image_data_access->getImageById($id)) {
    $image->scaleTo($size);
    header('content-type: ' . $image->content_type);
    header('content-length: ' . $image->length);
    echo $image->getBytes();
}


答:
To run any Java code, one needs the JVM (Java Virtual Machine) installed on the system.  On most systems, this is installed as part of the the JRE (Java Runtime Environment).  Developers typically install the JDK (Java Development Kit) which is a superset of the JRE that also includes compilers, debuggers, and associated tools.

Looking at Java SE Technologies at a Glance from Oracle, one can see the additional tools that are part of the JDK that do not come with the JRE.

Applets are part of the applet runtime plugin, the AppletViewer is part of the JDK.  One does not need the JDK to see an applet if the applet is hosted on a web page.

If this does not need to be part of a web page, one should instead consider using a stand alone environment that is part of the Java SE world.  Swing is under the "User Interface Libraries" in the chart on the oracle page which falls under the JRE.

Writing for a stand alone Java SE (rather than an applet) should make this easier to build and run.  See Java : Swing application on Wikipedia to get a very basic idea of a hello world app using this framework.  Note in particular the public static void main(final String[] args) { ... } method that exists within the class - this is how one invokes a Java SE application.

If one wanted to avoid needing a separate install of a JVM, it is possible though this comes with various restrictions.  The most well known of these is the commercial Excelsior package (its not exactly 'inexpensive').  Excelsior compiles to native code and includes a runtime (the JET runtime) that is capable of dynamically loading other .class files. There also exists gcj, though it appears to be... stale and without any recent (four years) updates.  Please read the status page and note that it likely won't fit your needs (java.awt: A lot of code exists, but not enough for use in real applications.)

If you are going to write a java application, your best bet is to have the JRE (one doesn't need the full JDK) on the target machine and build for that.  The JRE isn't that big and may very well already be on the target machines.

Title: How to run an applet like a desktop application without installing entire JDK?

Body:
I want to make a desktop application- an analog-clock with the option of setting alarms using java. For rendering all the graphics and the button features, a Swing applet is the answer.

But the problem is that I want to run the applet onto the desktop and so need an applet viewer like thing. Applet viewer comes with the JDK and I think installing entire JDK on a system for running just a simple alarm clock is really not a good idea at all because it will take a lot of space.

Is there a way out? Can I get just the applet viewer (or anything similar to that) instead of entire JDK so that I can run my applet?  Or is there any other way I can do my project using Java?


问:
IEC 62304 compliant Architecture definition
I am currently tasked with creating a software architecture for compliance with IEC 62304.  These regulations are notoriously vague, and do not provide any real substance as to what is required for a "software architecture".  The standard states

The manufacturer shall transform the requirements for the medical device software into a documented architecture that describes the software's structure and identifies software items.

Now I went to an applied computer science school, so the vast majority of my teachings were around how to actually write code and working on projects, so as far as I can remember, we never covered anything involving creating software architecture diagrams.

I've already basically written all of the software, but for regulatory submission purposes I need to create this documentation for the project.

So in short my question is this:  What exactly does a "software architecture" consist of?

答:
Software Architecture looking at the software from a high level. This will focus on how different software components interact with each other. It also consists of how outside systems can interact with your software system, or if you even allow outside systems to interact.
If you think of how a building architect does by designing a building, a software architect will design a software system. This involves documenting the software system. Some examples of how to document would be to create a requirements document, use case document, class diagram, state diagram, interaction diagram, help files to name a few.

As far as how much detail to use, I would say you will want to use enough to effectively portray what the system is supposed to do and what different messages mean when the system is not doing what the client is trying to do. They will need help documents and a glossary of terms, specially error messages.

For your team, I would use the requirements and other various documents to specify how the system works. This will help greatly with maintenance and enhancements. The requirements will help guide the team to determined when you have a finished, working product.


问:
Switching from ActionScript to JavaScript, tips for writing code?
I am quite comfortable with using actionscript3 and flash. I also have some experience with Java. But recently, I started learning JavaScript and node.js. I ultimately want to make a 3d game in threejs, but for now I simply want to make a chat application.

I want to get into the habit of using JavaScript. Unfortunately, I am finding it very difficult to start using JavaScript. The difficulties I am facing are

No suggestions for different methods and properties pop up, like they do in the Eclipse IDE and Flash Builder IDE. Like when you press dot after object, it shows all the methods and properties relating to that object and it becomes really easy to see what the parameters are and needed to be passed and stuff.

How to organize code? In ActionScript3, I could simply make different classes in different packages. I could then import and use those classes in one main file. How does it work in JavaScript?

Functions. I have seen people use anonymous functions in javascript. But I am compelled to write external functions as I am in the habit of it. What is better in JavaScript workflow? What do you advice?

How is code executed within a HTML file? So if I have several  tags and I declare a variable in one of them, can the tags below it and above it access that variable?

答:
My suggestion is to check out Haxe. You should use the stable version (2.10) for now, as version 3 is only in RC stage and many IDEs and 3rd party libraries do not yet have full support.

Haxe should be fairly familiar to you as an ActionScript developer. The way you would write an application would be to create markup and then query for the nodes you wish to add dynamic behavior to and manipulate them.

As for IDEs, the website contains a comprehensive list. If you're on windows, then you definitely will want to use FlashDevelop. It has a project template for haxe/js to get you started.

You might also be interested to have a look at NME, an ambitious project now backed by BlackBerry, that lets you use the Flash Player API on about every platform.

I suggest you join the Google Group or the IRC channel if you have any problems. The community is very active and friendly.

I should point out, there's a whole number of alternatives that you might want to consider (they all have some basic resemblance to AS3):

TypeScript

Dart

CoffeeScript

ScriptSharp

Personally, I favor Haxe over all of them, because it is both richer in features and not limited to JavaScript, but your needs may be different.


问:
Does map-reduce transmit the data and executable instructions?
When map-reduce divides a task and sends the data to each worker process, does it also transmit the instructions for how to operate on the data?

For example, let's say Google has some huge array of computers that use map-reduce to index webpages. If they wanted to temporarily use that same array of systems to do something else, would they have to reconfigure each system manually, or does map-reduce handle transmitting the new executable instructions to the workers?

答:
If you want to set everything up manually, you can do that.  At places like Google, though, you would expect some kind of highly automated infrastructure.

Generally, for purposes of portability and long-term maintenance, it is best to make the description of your map-reduce as independent as possible from these implementation details.  This is, in fact, the main virtue of map-reduce:  it allows you to describe a parallellizable task independently of the details of the system it runs on.


问:
Is imposing the same code format for all developers a good idea?
We are considering to impose a single standard code format in our project (auto format with save actions in Eclipse). The reason is that currently there is a big difference in the code formats used by several (>10) developers which makes it harder for one developer to work on the code of another developer. The same Java file sometimes uses 3 different formats.

So I believe the advantage is clear (readability => productivity) but would it be a good idea to impose this? And if not, why?

UPDATE

We all use Eclipse and everyone is aware of the plan. There already is a code format used by most but it is not enforced since some prefer to stick to their own code format. Because of the above reasons some would prefer to enforce it.

答:
I would say it isn't. A common code structure/format among a team is most definitely a good thing, but automatically enforcing it is not. This should be done by humans, not by the computer.

My biggest issues with the concept are

If I am writing code in one format and it is automatically reformatted, what incentive is there to actually learn that format?

Following that previous point, if you do not learn the format, the entire point of autoformatting (to make code more easily read and modified) is completely lost. You still have to take time to figure out the formatting as you are reading the code because you have not learned that format

I think it would be a jarring experience as a dev to write a class one day, close it, and return the next day to see it is completely different. That means that not only do others have to learn your code, you have to learn your code.

It could also encourage lazy coding. Instead of pushing the dev to learn the format, they can write in any format under the sun and it will automatically look the way everyone else wants it to. This goes back to #2 where you don't learn the style and still cannot read it correctly.

Now, I might be inclined to say that running an auto-format on a project that is all wrapped up would be a good idea. This would start every dev off on the same foot for the project when you go to fix/add features later on. During active development, however, I think it is a very poor choice.

Basically: Put the responsibility on the employee to learn the style of the company, don't force their code to be something that it isn't.


答: Walter Bright's Symantec/Zortec C++ compiler keeping up with compilers implemented by huge teams of programmers.  Later, his design and implementation of D.</p>


问:
How to manage github issues for (priority, etc)?
I'm new to github, and am looking for advice on how to manage issues.  I'm used to having priority and other ordering options but see that none exist.

How do others manages issues during the lifecycle of a bug/feature?

Thanks in advance.

答:
I use huboard.com to represent github issues in a Kanban board way, and then sort them by dragging and dropping within huboard.  It works pretty well if you're only interested in visualizing the priority, and knowing what to work next.

It actually stores the priority within the issue itself, as an HTML comment:

```<code>Your normal issue text here...
<!---
@huboard:{"order":465.0}
-->
</code>```

OwnerDisplayName: djf

Body:
I use huboard.com to represent github issues in a Kanban board way, and then sort them by dragging and dropping within huboard.  It works pretty well if you're only interested in visualizing the priority, and knowing what to work next.

It actually stores the priority within the issue itself, as an HTML comment:

Your normal issue text here...
<!---
@huboard:{"order":465.0}
-->


答:
Don't unit test it. Do functional/acceptance test it.

Unit tests should test every implementation, if you are not providing a new implementation then stick by the DRY principle. If you want to spend some effort here then you can enhance the original unit test. Only if you override the method should you write a unit test.

At the same time, functional/acceptance testing should make sure that at the end of the day all of your code does what it is supposed to, and will hopefully catch any weirdness from inheritance.

Title: Should I test inherited methods?


答:
I go for two kinds of labels in GH issues - the first relating to type of issue, and the second relating to priority:

bug

feature - (new stuff)

enhancement - (making existing stuff better)

question/discusstion - (discussing stuff)

Question/discussion may not be necessary, if you use the Wiki well. But I like it because it allows me to direct a question or an idea at a particular person.

Then there are three really simple priority labels:

now

soon

later

Easy, right?

Title: How to manage github issues for (priority, etc)?

Body:
I'm new to github, and am looking for advice on how to manage issues.  I'm used to having priority and other ordering options but see that none exist.

How do others manages issues during the lifecycle of a bug/feature?

Thanks in advance.


问:
Building automated unit tests for tools which don't have an xUnit implementation

Preamble

I have been bitten by the bug of automated unit testing. I feel the benefits and the confidence in a code base it can deliver.

I am also feel I have a reasonable intuition as to what parts of the code deserve to be unit tested. Code that has logic, code that might be messy (because it's dealing with some messy requirements) that you are happy to have encapsulated, that may have a few odd fringe conditions.

Unusual Context

At my place of work, we leverage a number of tools which are fairly niche. For the sake of argument I can certainly see that these tools deliver on features and efficiencies making them indispensable for getting their particular job done.

The challenge I have is that I certainly have implemented logic in these tools which my gut says "this should be covered with a unit test".

I have tested these bits of code...

In a throwaway fashion - try several inputs to exercise the code until satisfied it works - this has the downside of being lost effort when it comes to people maintaining the code in the future

In a less throwaway but manual fashion - writing up the test cases and steps to poke the code to produce output; with test data; such that the above throwaway tests are not thrown away - this retains the investment in time, but is slow and subject to people knowing about the tests and running them

In a slightly more automated fashion - with scripts to do the poking of the code; perhaps even check the output to a degree - this is more pleasant to re-run but is far from leveraging a mature framework in a consistent manner like when writing the xUnit style tests

While the progression feels nice, I feel I'm missing the xUnit experience I've become a fan of.

What kind of languages/platforms exactly am I dealing with here?

An ETL tool, akin to SSIS, called RedPoint Data Management: not open source so I'll describe, it has projects which have tools, these tools are linked by data flows, and some have some logic I wish to unit test

A composition tool, this for the uninitiated is a product which takes a data file and outputs a print file. Imagine XML in, PDF out.

DOS script functions: I promise this is a real feature of good'ol'fashioned DOS scripts, tutorial here

(I'll add this to the list, not strictly what I need help with, but may be more clear than the above if my tool set is difficult to empathise with) COBOL data transformations, using CopyBooks to specify the formats of the flat file inputs and outputs. When compiled results in one big-ball-of-mud binary even if functionally decomposed inside

The Actual Question

Are xUnit style tests fundamentally aimed at Object Oriented languages?

答:
I'm not entirely sure what sort of tools you are talking about here or what makes them difficult to test.

But might it be worth taking a look at ApprovalTests? This is a cross-language (Java, C#, VB.Net, PHP, Ruby) framework which sits underneath any unit test runner. It takes the approach of: instead of writing and test and specifying the expected result, you write the test, don't specify a result, run the test, and then it shows you the result. You approve it. From that point on, every time you run the test, it will pass if the result is unchanged from when you approved it, and fail (presenting you with a diff) if it has changed.

This is great for testing code that returns more than just simple scalar results (collections, XML documents, etc.) And because it runs under any of the major unit test frameworks, you don't lose any of your tooling around automation, etc.


答:
Good developers are creative people, give them some artistic licence. "Keep it simple" should be the programmers mantra. I have two rules:

Rule 1: Give variables / cursors / objects / procedures / whatever SENSIBLE NAMES. Unambiguous names that bring meaning and understanding to your code.

Rule 2: Use indentation to show the structure of your code.

That's it.


答:
No suggestions for different methods and properties pop up, like they do in the Eclipse IDE and Flash Builder IDE. Like when you press dot after object, it shows all the methods and properties relating to that object and it becomes really easy to see what the parameters are and needed to be passed and stuff.

This isn't really my cup of tea, but I'm sure there are Eclipse plugins that can do this to some extent for JavaScript. Due to the nature of functions and the object model in JavaScript, it would be much harder to do this for all cases than a language like Java.

How to organize code? In ActionScript3, I could simply make different classes in different packages. I could then import and use those classes in one main file. How does it work in JavaScript?

Check out RequireJS. As far as I know, it's the most commonly accepted method for formatting JavaScript "modules" (which are a JavaScript idiom).

Functions. I have seen people use anonymous functions in javascript. But I am compelled to write external functions as I am in the habit of it. What is better in JavaScript workflow? What do you advice?

You can write a lot of JavaScript without having to resort to anonymous functions, but anonymous functions make it easier. I think this is something that you can learn in time.

How is code executed within a HTML file? So if I have several  tags and I declare a variable in one of them, can the tags below it and above it access that variable?

The tags below it will have access to that variable. Code is executed linearly, and JavaScript's scoping is simple, limited, and oft criticized (but efficient if you know the caveats).

Title: Switching from ActionScript to JavaScript, tips for writing code?

Body:
I am quite comfortable with using actionscript3 and flash. I also have some experience with Java. But recently, I started learning JavaScript and node.js. I ultimately want to make a 3d game in threejs, but for now I simply want to make a chat application.

I want to get into the habit of using JavaScript. Unfortunately, I am finding it very difficult to start using JavaScript. The difficulties I am facing are

No suggestions for different methods and properties pop up, like they do in the Eclipse IDE and Flash Builder IDE. Like when you press dot after object, it shows all the methods and properties relating to that object and it becomes really easy to see what the parameters are and needed to be passed and stuff.

How to organize code? In ActionScript3, I could simply make different classes in different packages. I could then import and use those classes in one main file. How does it work in JavaScript?

Functions. I have seen people use anonymous functions in javascript. But I am compelled to write external functions as I am in the habit of it. What is better in JavaScript workflow? What do you advice?

How is code executed within a HTML file? So if I have several  tags and I declare a variable in one of them, can the tags below it and above it access that variable?