答:
These kinds of shops are horrible to work for.  I pity them as I would a wounded animal that is dying.

Old technology, overflowing with technical debt, constantly putting out fires, an ever increasingly disatisfied, angry and sometimes vendor-locked customer base... sound familiar?

You know that slight smile that you get from the overstressed manager that probably has a lower life expectancy because of the mess he has to deal with everyday?  That is the smile of somebody who has had almost 10 years of programmers new to the company telling him exactly the same thing.  Don't think for a second that with all the turnover that there hasn't been at least a handful of other developers all who came to the same conclusion.

They aren't there anymore because they failed to change things for the better and got frustrated and left like everbody else.  But by all means try to do this on your own, we tend to learn the most from our failures, not our successes.

They are sufferring under the quagmire of their self inflicted wounds and eventually when their customers find a way out or a better competitor comes along this place won't be there anymore.

If I were you I would start looking.  I have no patience for these kinds of software shops anymore.


问:
Does it make sense to avoid a framework when building a large webapp with PHP?
Being a PHP web application developer for several years now, I've had my share of MVCs and frameworks. At first I thought they were the best thing since sliced bread; everything seemed to be very easy to implement.

Now however, it seems that the more complex the application gets, the more hassle the framework introduces, so I have to develop workarounds to overcome them. Such workarounds are usually pretty daunting and complex since I have to delve down into the framework core code and make changes so that it behaves the way I want.

For example, in one of my projects where I use Slim(C)+Idiorm(M)+Twig(V) (which I believe is very flexible), I have to create a custom function just to display dynamic data in parent templates; without a framework I could have simply executed mysql_query() in the included file.

Okay, frameworks are cool if I'm creating a simple company profile website; I can just whip some code in one night and they're usually ready by the morning, and the amount of good coding practice and design patterns I've learned from them is very valuable.

But really, for a complex web application like an all-in-one web based school management system, frameworks usually get in the way of my business process like in the example above.

So my question is: is it okay to just go back to basics, and use standard PHP code and libaries for doing my next project where there might be a gazillion frameworks and libraries, provided I can sufficiently use good coding practices and follow sensible design patterns like MVC? My development team is pretty small: only 2 programmers and 1 designer. The other programmer agrees with my thoughts above.

答:
Working with a framework is helping you to speed up your development by not reinventing the wheel. Framework also provides you the tools to help you properly design your application (but it doesn't stop you from doing poor design decisions e.g. accessing the database directly from the view).

Sometimes when you need a custom functionality it may take longer to properly write it. But if you're constantly hacking and finding workarounds then you're working against the framework or the framework doesn't suit your needs.

Bottom line is this, using a big framework for simple projects (e.g. displaying a few fields from a database) can sometimes be overkill. For big or complex projects, use a framework.

ContentLicense: CC BY-SA 3.0


问:
How-to convince company to start documenting for legacy software
It has been less than a year since I joined my current company. Their majority of sales have come from a single product that has been alive since the last 10 years. However, there is minimal (if at all) documentation.

Not only do the developers in the company struggle with the lack of documentation but also there is a high amount of turnover, causing everyone to lose their time. This is because experienced developers have left the company and there is less and less resources to communicate/brain storm with.

Without getting into too much detail, I have suggested to the previous manager that there needs to be some sort of documentation (at least an Architecture document) that outlines the product. I also suggested using JavaDoc and other automatic documentation tools. These suggestions were responded to by slight smiles and statements of the sort "We do not have enough time", "We need short-term improvements right now" and even "The code itself should be the documentation" from the programmers themselves.

I have already wasted enough time trying to find out if what I needed per requirement/bug had existed in this big (really) code base. I am looking for any suggestions that you might give regarding the need of documentation. Or, rather, if this is a lost case for this legacy system or organization.

答:
Aside from pushing for documentation (which is important), I would also suggest pushing for tests to be written (if they haven't been already and I'm willing to bet they haven't been). As Michael C. Feathers talks about in his book Working Effectively With Legacy Code, tests are a good way to deal with the cluttered code in a legacy application. Write tests that will help you to understand how certain parts of the code are supposed to work. This in turn will help you to document the architecture of the application as you should gain a better understanding of the code, as well as help with any refactoring you will need to do.

Good luck! I feel your pain as well.


问:
Jenkins without Automated Tests
I know that Jenkins is focused on continous building/testing, monitoring of batch jobs about the project. We have a legacy project which such condition :

1)Has a development team.

2)It has SVN for source code management

3)Some cronjobs for some operations.

4)Compile&Build don't take too much time, there is no very complex dependencies.

5)It doesn't have any automated test/junit classes and will not have.

I'd like to ask to experienced users about Jenkins, is it still worth to use Jenkins for central build&management of the project ?

答:
It is worth it, as others have said, just for the stable, automated build process itself. But just having it and in use could begin to change some internal practices you didn't even know you wanted to change in the first place (not saying that's your situation, just that it's possible).

Case in point, I recently managed a group that, over the course of the year, went from nearly the same type of environment as you listed to one that incrementally used more features of CI (Jenkins, specifically) and to their benefit.  For instance, the group switched from a mix of SVN and git to a mix of public and private GitHub repos with post-commit hooks back to Jenkins, allowing them to better distribute and manage their different types of projects.  Additionally, test coverage improved -- included going from none to some, and from some to much more -- including from some folks who just didn't like writing tests, because seeing everyone else's tests break or not made them feel like they had to keep up and/or join the fun (this was a neat thing to watch, don't know how common it is!).  Deployment moved from batch scripts and manual processes to push-button deployment of builds, with an eye toward never doing it the "old way" again.

Like most tools, it'll only be as useful as you make it, but even if you use it for the most minimal reasons, I'm a Jenkins fan.

Edited to add: Apropos of nothing, today is Jenkins's birthday.

Title: Jenkins without Automated Tests


问:
Determining the right amount of documentation
Where I currently work the general approach is -

avoid documentation as much as possible

Only document if a different team will need it

just for clarification, I don't mean code-documentation - this we do, I mean all the documentation surrounding the design process - if it's UML or DB Schemas, class diagrams and word documents with specifications and the likes.

I will list my Boss' reason to not document:

it's time consuming - focus on implementing

if design change - then the documentation should change, double trouble

in the end you just get hundreds of pages nobody wants to read, and nobody really edits so by time it will get out of date

Its a pain - nobody really wants to do it

Now I realize we do work faster, but I also remember the time getting here and diving straight to some old code, not understanding anything.

Actually, I still don't get most of this old code, and sometimes when I get in I see many patches from different developers trying to make small tweaks.

I really think lack of documenting promotes these kind of patches and lack of system understanding in a broad sense.

my question is:

How can we balance documentation so that we will promote continuous knowledge among the team and still be fast and efficient?

答: You cannot escape allocating time to write proper documentation. Balance it however you wish depending on how much work you are given, but leave a good 15-20% of your time to document what you have done. Everyone on the team has to be on board with this, including your manager, otherwise you will only be documenting for the benefit of others and will get nothing in return. Documenting must be an integral part of your development process.</p>


问:
Is it possible to compile Java into machine code? (Not bytecode)
Can you have Java compiled straight into machine code?

I want to do this so I have control over what platforms it's used on, and don't know C,C++ etc.

答: It appears that the GNU Compiler for Java can convert Java source code into either Java bytecode or machine code. It can also convert existing Java bytecode into machine code. However, the last news is from 2009, so I'm not sure how current it is and if it can handle the latest features of the Java language.</p>


问:
Factory design pattern - getting the types from a table
I've implemented a generic factory as described here

I need to register elements to the factory hard-code like this:

```<code>Factory.Register(1, typeof(MyClass));
</code>```

this factory will have to be correlated with a simple domain data type table [id,Display], in this case id 1 is related to MyClass.

I was thinking to add a column to that table with the qualified type, so I can simply retrieve the id to types. table will be [id,Display, typeName]

and I will use the factory like this:

```<code>Factory.Register(id, Type.GetType(typeName));
</code>```

I tried it and it's working ok.

is this a good design?

are there any security flaws?

is there a better way to do things?

答:
This ties the db design to the programming language, which, in my opinion, is something you would want to avoid.

A simple alternative would be to add a key to the table and have a way to map that key to a type in the programming language of your choice. This may not be such an elegant solution as it may require a switch statement, but it is the better architecture despite the shortcomings of my suggested implementation. This way if you have to use the table in another language, you will be ok.

At the very least, add the language agnostic key to your current table and add a cross reference to your fully qualified type name.


答: It might be better to detect the operating system using System.getProperty(“os.name”).  That would let you choose to support more than one OS, but exclude others.</p>

Title: Is it possible to compile Java into machine code? (Not bytecode)

Body:
Can you have Java compiled straight into machine code?

I want to do this so I have control over what platforms it's used on, and don't know C,C++ etc.


答:
At my last few employers, we've had a "development" wiki.  Significant chunks of functionality (new import / export feed, how the security subsystem works, where does the system store uploaded documents, etc.) all get documented on there.  It's usually a mandatory item to be completed before the code review step.  There's usually a bit of resistance to it at the beginning, but once someone needs to go look up a bit of information and it's on there, you've got another convert.

The nice thing about having it in a wiki format is that you're much less inclined to do all the pretty Word formatting and such and just write out the real information you need to save.  Most (if not all) wiki packages will allow you to upload documents or images (like Visio UML diagrams, or UI wireframes), so you can have visual pieces as well.

Like most things, I think you should aim to do the minimum amount that could possibly work.  That's not the same thing as none though.

Title: Determining the right amount of documentation

Body:
Where I currently work the general approach is -

avoid documentation as much as possible

Only document if a different team will need it

just for clarification, I don't mean code-documentation - this we do, I mean all the documentation surrounding the design process - if it's UML or DB Schemas, class diagrams and word documents with specifications and the likes.

I will list my Boss' reason to not document:

it's time consuming - focus on implementing

if design change - then the documentation should change, double trouble

in the end you just get hundreds of pages nobody wants to read, and nobody really edits so by time it will get out of date

Its a pain - nobody really wants to do it

Now I realize we do work faster, but I also remember the time getting here and diving straight to some old code, not understanding anything.

Actually, I still don't get most of this old code, and sometimes when I get in I see many patches from different developers trying to make small tweaks.

I really think lack of documenting promotes these kind of patches and lack of system understanding in a broad sense.

my question is:

How can we balance documentation so that we will promote continuous knowledge among the team and still be fast and efficient?


问:
Which (programming) specialities are needed in a good web development team?
At first glance, I'd say a good programming team needs to understand the following matters:

The details of the core language / framework

HTML, (asynchronous) javascript

SQL / data model

Usability / UI design

Security

Project management.

If this team is not complete: what is needed?

答:
A good development team is nothing without some support:

One major role that's missing is IT: systems administration, networking, etc. There are a lot of developers whose knowledge of how computer systems work stop at the compiler.

I'd also add a manager to handle vendor contracts and other support aspects of a development team.

ContentLicense: CC BY-SA 2.5


答:
I've found ANY documentation is better than NO documentation.  The appropriate amount is usually determined by the amount of time we have to do it, or by how much we hate support phone calls and emails.

It appears that your current team members have some unrealistic expectations of their memories, or they are ashamed of their writing skills, and are unwilling to practice.

I realize I am in a minority (English major who got into software engineering in graduate school) here, as I don't find documentation as a chore. It's a valuable professional tool. I may not find writing as difficult to do as some of my coworkers, but that's mostly because I have more practice at it.  I don't consider a project finished unless it has documentation, and I usually write it for purely selfish reasons: so I can give people something to read instead of taking phone calls and emails, or so I can remember what we were talking about last month, or so I can refer to how I did something if I need to support it in the middle of the night.

The best way to approach documentation is to write it AS YOU GO, exactly like writing test code.  It's amazing how a few pre-written templates (with headers, stubs of code, etc.) can make documentation easier and faster to do.  This way you can capture change as it happens, and you have less ground to cover over time.  You are more efficient this way, since you can refer to documentation as you need it, and you change it along the way.  Doing so in a wiki, for example, makes updates easier, and you can avoid document version issues if the latest and greatest is always online in the same place, and you can just send links to people who need to read it.

If you spend a little time documenting, you will ALL work faster, especially when someone new joins the team, since they won't have to spend all that time figuring everything out.  Figuring stuff out is a fun part of our jobs, but it's not fun when you have to do so in a hurry to fix production.  We'd all save a lot of time if we all wrote a couple more notes.

Does your team have the same issues with testing, or writing test code?  If not, this will be an easier sell.

Your documentation is useful in many ways:

1) To you, right now, and to your coworkers, as you work on the project.

2) To your customers. Having documentation (including diagrams) that you can show users makes discussions in meetings easier, especially if you are discussing complicated systems.  Even if the documentation is incomplete, it's a place to start from.

3) To the people who will inherit your work (which may even be you, in three years). Many of my younger co-workers think they'll remember stuff forever.  I know I won't remember it past this week if I don't write it down.  Having documentation saves you from having to spend half a day to remember how you structured something, and having to figure it all out again.

4) To you and others, if the situation gets political or contentious.  As someone who takes notes in meetings, to keep myself awake and fight boredom, I have often been the only one with the written version of a decision.  The person who wrote it down wins the dispute.  Remember this the next time someone says "Remember that meeting we had this past winter in conference room 4, when we were going over X?  Fred was there, and who's that guy from Accounting?"


答: What you describe has been called "abstraction induced complexity" in the past. The only paper on managing it is: Managing Abstraction-Induced Complexity by David Keppel. Keppel would suggest that the frameworks have a design that causes abstraction induced complexity.</p>

Title: Does it make sense to avoid a framework when building a large webapp with PHP?

Body:
Being a PHP web application developer for several years now, I've had my share of MVCs and frameworks. At first I thought they were the best thing since sliced bread; everything seemed to be very easy to implement.

Now however, it seems that the more complex the application gets, the more hassle the framework introduces, so I have to develop workarounds to overcome them. Such workarounds are usually pretty daunting and complex since I have to delve down into the framework core code and make changes so that it behaves the way I want.

For example, in one of my projects where I use Slim(C)+Idiorm(M)+Twig(V) (which I believe is very flexible), I have to create a custom function just to display dynamic data in parent templates; without a framework I could have simply executed mysql_query() in the included file.

Okay, frameworks are cool if I'm creating a simple company profile website; I can just whip some code in one night and they're usually ready by the morning, and the amount of good coding practice and design patterns I've learned from them is very valuable.

But really, for a complex web application like an all-in-one web based school management system, frameworks usually get in the way of my business process like in the example above.

So my question is: is it okay to just go back to basics, and use standard PHP code and libaries for doing my next project where there might be a gazillion frameworks and libraries, provided I can sufficiently use good coding practices and follow sensible design patterns like MVC? My development team is pretty small: only 2 programmers and 1 designer. The other programmer agrees with my thoughts above.


问:
Studies of open source software adoption
I'm not 100% sure this is approriate here, but I figure the area of study is particular to programmers, since it's open source software. If it's better posted somewhere else then please say so and I will post it there.

Can anybody point me in the right direction of any studies on businesses and consumers adopting open source software? Ideally, I'd like some qualitative information on why both parties choose (not) to adopt open source software, but raw numbers are good too.

Any relevant experiences and case studies of this from users would be welcome as well.

答:
I've been able to find a couple of references with regards to this.

http://dmst.aueb.gr/dds/pubs/conf/2009-MCIS-OSSAdopt/html/SG09.htm

Also a reference to a similar question with some references

You can probably follow the bibliography of the on the first link to see if you can get the raw data but in general what would happen is that the companies won't discuss anything that might be seen as a competitive advantage for example: Cost savings from adopting Open Source software vs. the commercial versions, etc.

As far as the end users are concerned you would have to look for download statistics by package to actually get some sort of relevant information.


答:
Frameworks are still going to be used for any language in modern, especially for large projects. The larger a project gets the more important a framework is, so you know where the logic is for everything, and every feature has a similar layout.  It makes modifying a project easier and learning it easier when you know where to look for all data access, or all presentation, or where business rules are managed.

It is necessary to pick a framework that fits the project though, an enterprise solution requires an enterprise capable framework. This is the problem you are going to run into when using PHP. Many (most) frameworks aren't intended to be used at a large scale, they work fine for smaller personal sites though. For something like the school management system you mention, its going to require a more robust framework, and it may take some time to find a proper framework in PHP.


答:
There was a presentation way back by the Django developers, which I am having trouble finding now, but they talk about the "valley of efficiency" where a framework makes you more productive.

Assuming you have no knowledge of the framework when you start a project, your productivity initially will be very low - you will be learning the convention of the framework rather than the idiom of the language (which hopefully you already know).

After a short amount of time, you will have picked up on the conventions and this is where frameworks really shine - suddenly your productivity is through the roof and you're progressing and amazing speed through development.

Eventually, though, the project will become of such a size that the framework is more of a constraint than a boon, and you will see  yourself railing against the framework to try and implement some features.

In the presentation, they mention that of course if you already have knowledge of the framework's conventions then smaller sized projects do not have the initial hindrance to efficiency.

Thus, for small projects (in my experience, anything under ~500 hours) your efficiency with a framework will be greater, likely, than your efficiency without. Once you get into a certain threshold (between 500 and 800 hours, IME) then you start realizing that there are limitations to what the framework can offer.

With that said, frameworks offer a much greater benefit than just efficiency - a framework like Symfony or Django or (I am assuming) Rails provides a convention that allows a team to flex dynamically and also allows clients or product owners to change their staff without requiring the new resource to completely relearn a new system - if they are familiar with the convention of a framework, and that convention has been followed, they will be much more productive initially than otherwise.


问:
Dealing with management that does not see value in improvements that are not immediately visible to the user
I can understand schedule pressure.  You want to please your users, as they are the lifeblood of the company. However, it is also true that certain changes will make everything easier down the road. Unfortunately, management in my organization has an instinctive resistance to such changes and this resistance is so strong that it gets in the way of long-term improvements.

For example, Apple recently introduced Automatic Reference Counting for iOS programs.  This is a major improvement over the manual retain/release calls one previously had to use.  The code is easier to write and easier to maintain. The changeover itself is likely to produce some crashes. But once those are worked out, the number of random weird crashes is likely to go down.

I recently mentioned to my boss that I wanted to switch to automatic reference counting.  His response was that he wanted to concentrate on visible improvements. It is likely that this response was in turn driven by pressure he is getting from above him - and probably right from the CEO.

There are a lot of similar examples.  The common thread is that something needs to be fixed but the short-term costs of the fix outweigh the short-term benefits, where "short term" is defined as "within the next few weeks."

How should I handle the situation?

EDIT:  Thanks for the responses.  Keep 'em coming.  Because it is relevant to my situation, I should make it clear that my manager and the CEO are both programmers -- though the CEO may by now have forgotten what this is like.  Apparently their programmer sides have been overwhelmed by other pressures.

答:
You obviously work for a pointy-haired boss (PHB). He doesn't program anymore, if ever, and if he did he probably wasn't really any good (although he does like to drop in phrases like "const correctness" and "segmentation fault" so that the guys know he's earned his stripes) - that's how he got singled out for management.

The CEO (who practically has a Mohawk) likes the PHB because the PHB delivers features. Every sprint he proudly demonstrates a new tick-box (slightly misaligned, with an ambiguous label), a sparkly icon (not yet working in any environment but 8-bit color over Citrix) and a form (that has random crashes due to race conditions in the bespoke xml variant based C implemented local database that no one on the dev team dare touch because it was written by one of the old guard dev legends 10 years ago and does EVERYTHING with macros with 5 letter names, whether they needed 5 letters or not).

The programmers who actually do the "work bit" (you know that bit that happens, inconveniently after all the real work like drawing circles on whiteboards, shouting, and eating miniature Battenburgs is done) know that in a sane system the work that just took 10 guys 10 days to laboriously hack out of the unmaintained jungle, would probably amount to one or two man days, including the testing. But to get the system from where it is to sane might take 6 months of genuinely hard work, with little in the way of obvious external reward.

The PHB knows that in 6 months, by hook or by crook, he can get thirty or forty new features into the application that the salespeople (who must be magicians given what they're actually selling) can be used to tempt new purchases and upgrades.

However to give the PHB his dues: without those tick-boxes and forms sales may well stagnate or decline, a competitor may gain market share, and that might be worse than the alternative.

The conclusion that I've come to is that the only way out of the quagmire is to work in a new start-up, with a few people who share your vision of how software should be done and then doggedly stick to that philosophy (I'm still working on getting there!)


答:
Documentation should tell you WHY you did something while you leave the HOW part to the actual code and WHAT part to the unit tests. Anything more is a pain. This is usually good enough for smart people who just want a starting point.

Also, don't forget to maintain an overall high level architecture of each big component of your code base. Makes it very easy to induct new team members.

Finally, whenever you add a wacky fix, link to your bug database from a comment - very useful.


问:
Private variable vs property?
When setting a value to a variable inside of a class most of the time we are presented with two options:

```<code>private string myValue;
public string MyValue
{
   get { return myValue; }
   set { myValue = value; }
}
</code>```

Is there a convention that determines how we should assign values to variables inside of our classes? For example if I have a method inside the same class should I assign it using the property or using the private variable. I've seen it done both ways, so I was wondering if this is a choice or performance is a factor (minor, probably).

答:
Generally, I would say assign to the field in the constructor and use the property everywhere else. This way, if someone adds functionality to the property, you won't miss it anywhere.

It certainly isn't a performance factor. The optimiser will inline a simple get or set for you and the final MSIL code will probably be identical.

Title: Private variable vs property?


答:
If there is any chance that those property get/set implementation will change sometimes later (for example, you want to rise an event when calling set, or you will add some lazy evaluation mechanism later to your get function), then it may be a good idea that your code inside the class will use the property in almost all cases except for the - most probably rare - cases where you explicitly don't want those event or lazy evaluation mechanisms to be used.

Anyhow, whatever you will do, there is a good chance that when you change the property implementation later in such a way, you will have to look at all places inside your class accessing those property to check if really the property shall be accessed or the private variable shall be used.

Title: Private variable vs property?

Body:
When setting a value to a variable inside of a class most of the time we are presented with two options:

```<code>private string myValue;
public string MyValue
{
   get { return myValue; }
   set { myValue = value; }
}
</code>```

Is there a convention that determines how we should assign values to variables inside of our classes? For example if I have a method inside the same class should I assign it using the property or using the private variable. I've seen it done both ways, so I was wondering if this is a choice or performance is a factor (minor, probably).


答:
Depends.

First you should prefer automatic properties when possible:

```<code>public string MyValue {get;set;}
</code>```

Second the better approach would probably be to use the properties, if you have any logic there you should probably be passing through it yourself, especially if that logic is thread synchronization.

But you should also take into account that it might hamper your performance (a little bit), if you are synchronizing incorrectly you can deadlock yourself, and sometime the correct path is to go around the logic in the property.

Title: Private variable vs property?

Body:
Depends.

First you should prefer automatic properties when possible:

public string MyValue {get;set;}

Second the better approach would probably be to use the properties, if you have any logic there you should probably be passing through it yourself, especially if that logic is thread synchronization.

But you should also take into account that it might hamper your performance (a little bit), if you are synchronizing incorrectly you can deadlock yourself, and sometime the correct path is to go around the logic in the property.


答:
Well, the straight-to-the-point approach would be to just assign it to the variable itself, since you're inside a class' method and you control the class' behaviour, anyway.

But the whole point about properties is that they abstract the variable away. Whereas such a simple property as in your example has completely no use over just a simple public member variable, properties usually do (or should do) additional things inside their getters and setters. And if you want these things done automatically when changing the property inside the class, then it is of course cleaner to work on the property instead of the variable to not have to change each variable assignment when the property setting behaviour changes.

You just have to reason about it conceptually. The property is actually a handle to access some internal state of the object, which may be comprised of more than one member variable. So you have to ask yourself if you want to change the underlying internal state only (or only part of it) or the abstract property representing this state at a whole, and most times it's indeed the latter since you usually want your object to always have a consistent state.

Title: Private variable vs property?


问:
Cost of design based on the cost of programming
What is your methodology when you need to determine the cost of UI design if you know the cost (work hours) of programming in some project?

Let's say, programming of logic in some project cost X dollars. Is there some general percentage (like 30% of programming costs) which can help determine the cost of design?

The area of interest is mobile phones development (mainly business tools and 2D games, not 3D at all). There is less design work here comparing to a web design or a PC game design.

答:
The problem here is that there is no widely-accepted definition of what design is in software development. For example, for many people the line between design and coding cannot be drawn sharply, and some see design and coding as being the same thing:

http://www.developerdotstar.com/mag/articles/reeves_design_main.html

From this point of view, the cost of design is the cost of programming. Other people think "drawing some UML diagrams" or "creating some GUI layout" is design - especially when this task is assigned to some non-programmers. If that's the case, ask those "designers" about their effort, and you will easily find your design cost.

So, first make clear how you define design in your team, and if this task is done in your team somehow "separately from coding". If you cannot separate the design task clearly, don't try to separate in form of costs, that will make not much sense.

EDIT: from your comment, you made clear that you meant UI design (even though you forgot to change the misleading title of your question). Nevertheless, you have to define where you draw the line between "UI design" and "coding". Is UI design for you just "draw some forms with pencil and paper"? Is it the design of the exact behaviour of your UI from the perspective of a user? Is it the design of your inner workings of your forms, for example, when you design your application as an MVP architecture? Based on that (and based on the requirements of your application, of course,) you may come to different conclusions what the percentage of UI design might be in your case.


答:
I think you are going about it in the reverse. If you magically know the exact programming cost (I don't see how this is possible though), then you probably don't need the design phase, and probably the problem you are trying to solve is very simple.

If you mean how to estimate the UI Design, that is a different territory. Depending on the field, sometimes UI is tacked on as a late addition where you may get away with a trivial estimate like x% of project time. The fields you mentioned here though are 100% user facing, So I would start with a UI design alongside the programming effort itself. Even then, it is hard to generically quantify it as a % of the total development time though - we need more context. After all, there have been so many games that had excellent AI etc., but turn away a ton of people because they have bad interface / graphics design. FWIW, people even rail on the wildly successful Skyrim because it got the UI design wrong for PC (The controls are more controller tuned rather than kb/mouse tuned).

Title: Cost of design based on the cost of programming

Body:
What is your methodology when you need to determine the cost of UI design if you know the cost (work hours) of programming in some project?

Let's say, programming of logic in some project cost X dollars. Is there some general percentage (like 30% of programming costs) which can help determine the cost of design?

The area of interest is mobile phones development (mainly business tools and 2D games, not 3D at all). There is less design work here comparing to a web design or a PC game design.


答:
Here's why your request for automatic reference counting is being rejected:

It's not an improvement. Once you have anything larger than hello world, any change is going to wrong direction. No amount of refactoring is going to change the fact that if you need to do changes, it's always going to wrong direction. The trick is to know when your changes are significant enough that it is still worth the risk of causing new issues. Your management have clearly said that if end users cannot see it, it's not worth the risk.

Reference counting is completely crazy feature. You saw some existing big famous company implement some feature, and immediately thought that you need the same feature. Well, it's very likely your codebase is completely different from what apple is using. Probably reference counting is not going to work, or it's just waste of time. You should find a different way which does not require spreading reference counting primitives everywhere in your code. Probably your refcounting plan requires thousands of modifications in the codebase, most of those changes are not necessary. Just waste of time and money.

You're solving the wrong problem. Management usually knows what kind of problems there are in the system. Some irrelevant memory leak problem that the refcounting solution is solving is not one of them. Focus on real problems and not some imaginary problems with how computers handle memory.

It takes too long time to implement it Apple is slightly bigger company than your insignificant team with few programmers and some managers. They can do big changes by just paying the price. If it takes few millions to implement something, it's peanuts. If small companies tries to do the same thing, they're going to run out of money fast. Software development is already very expensive; adding unnecessary costs is not going to help one bit. One irrelevant feature like memory management is going to open the floodgates: after they approve it, half your programmers want their own "improvement" to be implemented. It's neverending story and the company could be doing something useful instead.

Here's some steps you can use to handle the problem:

Drop the feature

Find out what is the real problem

Start doing something useful

Carefully plan how you use your time

Find out how your improvements are bringing in money

Choose only the features that bring in most amount of money

Realize that the programming aspect of software development is only small part of the whole system -- improvements to it is never going to be worth the time

Title: Dealing with management that does not see value in improvements that are not immediately visible to the user

Body:
I can understand schedule pressure.  You want to please your users, as they are the lifeblood of the company. However, it is also true that certain changes will make everything easier down the road. Unfortunately, management in my organization has an instinctive resistance to such changes and this resistance is so strong that it gets in the way of long-term improvements.

For example, Apple recently introduced Automatic Reference Counting for iOS programs.  This is a major improvement over the manual retain/release calls one previously had to use.  The code is easier to write and easier to maintain. The changeover itself is likely to produce some crashes. But once those are worked out, the number of random weird crashes is likely to go down.

I recently mentioned to my boss that I wanted to switch to automatic reference counting.  His response was that he wanted to concentrate on visible improvements. It is likely that this response was in turn driven by pressure he is getting from above him - and probably right from the CEO.

There are a lot of similar examples.  The common thread is that something needs to be fixed but the short-term costs of the fix outweigh the short-term benefits, where "short term" is defined as "within the next few weeks."

How should I handle the situation?

EDIT:  Thanks for the responses.  Keep 'em coming.  Because it is relevant to my situation, I should make it clear that my manager and the CEO are both programmers -- though the CEO may by now have forgotten what this is like.  Apparently their programmer sides have been overwhelmed by other pressures.


答:
There is no such percentage. In the same way, there is no percentage of time you'll work on security, for example. One application must be secure and will require half of your staff to work on it. Another application doesn't have any security concerns, so the impact on your schedule will be minimal.

The time required to do visual design depends on the requirements. It's not about the type of software (you quoted business tools, web applications and games).

If my customer doesn't care about visual design of a website, I'll spend a few hours creating something basic, and use the remaining two months of work for other, more important aspects.

If my customer cares about user interaction, I'll spend a few weeks creating carefully the different aspects of interaction design, polishing the visual aspect, etc., while caring less about the aspects which don't matter for this customer for this project.

In both cases, it's still a web application.

In general, you have two ways to group tasks when creating an application.

The first one is sequential: it's the states you need to do in order to achieve success in your project. You start by gathering functional and non-functional requirements, you work on the specification, architecture and application design, you create tests, you write the actual code, you deploy and maintain the application.

Here, depending on the level of seriousness and the scale of the project, you have the similar percentages from project to project. For a home-made tiny application, you'll always have 0% to 5% for requirements. For a large-scale enterprise application requiring exemplary QA, the time you'll actually write code will be 15% to 20%.

The second one is parallel: it's the things you have to do, given that they are nearly independent from the point of view of project management and the things you may do or skip. It includes security, visual design, portability, performance, etc.

Here, percentages are irrelevant. It's more a question of priorities, not the scale of the application and the required QA level. A business app may have an outstanding user experience, because the stakeholders know that the project will fail otherwise or that the UX is a competitive edge. Another business app may have nearly no design at all, because there is nothing to innovate in terms of design.


答:
I would take it a step further, and bring it to 3 cases.  Although there are variations on each, this is the rules I use the majority of the time when C# programming.

In case 2&3, always go to the Property Accessor (not the field variable).  And in case 1, you are saved from even having to make this choice.

1.) Immutable property (passed in to constructor, or created at construction time).  In this case, I use a field variable, with a read-only property.  I choose this over a private setter, since a private setter does not guarantee immutability.

```<code>public class Abc
{
  private readonly int foo;

  public Abc(int fooToUse){
    foo = fooToUse;
  }

  public int Foo { get{ return foo; } }
}
</code>```

2.) POCO variable.  A simple variable that can get/set at any public/private scope.  In this case I would just use an automatic property.

```<code>public class Abc
{
  public int Foo {get; set;}
}
</code>```

3.) ViewModel binding properties.  For classes that support INotifyPropertyChanged, I think you need a private, backing field variable.

```<code>public class Abc : INotifyPropertyChanged
{
  private int foo;

  public int Foo
  {
    get { return foo; }
    set { foo = value;  OnPropertyChanged("foo"); }
  }
}
</code>```

Title: Private variable vs property?

Body:
I would take it a step further, and bring it to 3 cases.  Although there are variations on each, this is the rules I use the majority of the time when C# programming.

In case 2&3, always go to the Property Accessor (not the field variable).  And in case 1, you are saved from even having to make this choice.

1.) Immutable property (passed in to constructor, or created at construction time).  In this case, I use a field variable, with a read-only property.  I choose this over a private setter, since a private setter does not guarantee immutability.

public class Abc
{
  private readonly int foo;

  public Abc(int fooToUse){
    foo = fooToUse;
  }

  public int Foo { get{ return foo; } }
}

2.) POCO variable.  A simple variable that can get/set at any public/private scope.  In this case I would just use an automatic property.

public class Abc
{
  public int Foo {get; set;}
}

3.) ViewModel binding properties.  For classes that support INotifyPropertyChanged, I think you need a private, backing field variable.

public class Abc : INotifyPropertyChanged
{
  private int foo;

  public int Foo
  {
    get { return foo; }
    set { foo = value;  OnPropertyChanged("foo"); }
  }
}


答:
I always use the public property.

Often some logic which should always run when the property is set is added to the set method of a property, and setting the private field instead the public setter will bypasses any logic there.

You have a comment about MVVM leading to this question, and I feel this is even more important when working with MVVM. Many objects raise a PropertyChange notification the setter, and other objects can subscribe to this event to execute some action when specific properties change. If you set the private variable, these actions will never execute unless you also manually raise the PropertyChanged event.

Title: Private variable vs property?


问:
How do you share your craft with non programmers?
Sometimes I feel like a musician who can't play live shows. Programming is a pretty cool skill, and a very broad world, but a lot of it happens "off camera"- in your head, in your office, away from spectators.

You can of course talk about programming with other programmers, and there is peer programming, and you do get to create something that you can show to people, but when it comes to explaining to non programmers what is it that you do, or how was your day at work, it's sort of tricky.

How do you get the non programmers in your life to understand what is it that you do?

NOTE: this is not a repeat of Getting non-programmers to understand the development process, because that question was about managing client expectations.

答: I think a good analogy is building a factory. Most people have seen something like "How it's Made" where you see some item getting shuffled through different conveyor belts and machines with hopefully a finished product coming out at the end.  I tell people that I build things like that, but instead of being physical factories working on physical items, they are virtual and they work on data.  Of course this is not a good analogy for everything kind of programming, but I think if gives a good idea of the complexity and does parallel many kinds of applications.  </p>


答:
Generally, it's up to you what you should do with a property and its backing field when getting/setting.

Most often, just to be consistent across code, you should use public accessors wherever they are available and appropriate. That allows you to refactor with minimal code change; if the method doing this setting needs to be stripped out of the class and put somewhere else where the backing field is no longer available (like a base class), who cares? You're using something that's available wherever the class itself is to do the job. The backing field, in most cases, is an implementation detail; nobody outside your class should know it exists.

The main situation I can think of when you should use the backing field and NOT the property accessor is when the accessor has additional logic (validation, or updating other state information in the class) which you don't want to run. Initial population of an object is an example; you may have a class that uses two property values to calculate a third, which is also stored in a backing field (for persistence reasons). When initializing a new copy of that object given data from the DB, the property accessors which each recalculate the third value may complain if the other needed value is not set. By using the backing fields to set the initial values of these two (or three) properties, you bypass the validation/calculation logic until the instance is in a consistent enough state for the logic to work normally.

Title: Private variable vs property?


问:
Modern Java implementation of Blackboard Pattern?
Is there room for a practical modern application in Java of the Blackboard Pattern detailed in "The Pragmatic Programmer"? Is there any particular library that attempts to assist in the implementation of this concept? What is the general consensus on this pattern in the present software community (especially Java)?

Though the idea is intriguing, I have a feeling that this portion of the book may be outdated.

In case you are not familiar with this concept: http://flylib.com/books/en/1.315.1.55/1/

答:
Well, design patterns are exactly that; conceptual patterns for the development of algorithms, not necessarily implementations of said pattern that work in the general case. As such, libraries that provide "built-in" functionality may use a particular pattern, and may even be shining examples of the use of said pattern, but they aren't THE pattern. You don't need a StrategyProvider class that can be configured to meet any need, you just define a set of classes and structure them to follow the Strategy pattern.

The idea is intriguing. It looks like it would work well for document organization, flow-charting, social networks, etc etc. However, its implementation in each of those scenarios would be quite different, and while there's overlap it may be impossible to create one implementation that meets the requirements of all these scenarios, without exhibiting "inner-platform effect" (an object/library/application so complex and configurable that it basically becomes a reimplementation of the IDE used to build it).


答:
As a different take to the other 15 answers...

Instead of explaining the details of my work (programming), I try to focus on the solutions that the work solves, i.e. what problems do the systems/software I build actually solve for the user. That's usually a non-programming domain, unless you're writing a compiler or something, in which case you'd have to explain why that's useful.

That way, it makes it easier for people to grasp that it's complex nature and how it relates to the "real world".

As an analogy, as a medieval smith, I'd probably explain (to lady in the local tavern) that I make swords to hack the enemy into pieces, not how I temper steel and hammer on it with a certain angle and force (unless they ask). Hopefully, she'd understand that hacking an enemy into pieces is useful (...) and can be tricky to do (shortage of steel, armored foes, smoky workplace, etc) and thus you gain some appreciation for performing a complex task.

(So, casting anvils would be equivalent to making compilers, and you'd have to explain what they're used for... )

Title: How do you share your craft with non programmers?

Body:
Sometimes I feel like a musician who can't play live shows. Programming is a pretty cool skill, and a very broad world, but a lot of it happens "off camera"- in your head, in your office, away from spectators.

You can of course talk about programming with other programmers, and there is peer programming, and you do get to create something that you can show to people, but when it comes to explaining to non programmers what is it that you do, or how was your day at work, it's sort of tricky.

How do you get the non programmers in your life to understand what is it that you do?

NOTE: this is not a repeat of Getting non-programmers to understand the development process, because that question was about managing client expectations.


问:
Unit-testing of inherently random/non-deterministic algorithms
My current project, succinctly, involves the creation of "constrainably-random events". I'm basically generating a schedule of inspections. Some of them are based on strict schedule constraints; you perform an inspection once a week on Friday at 10:00AM. Other inspections are "random"; there are basic configurable requirements such as "an inspection must occur 3 times per week", "the inspection must happen between the hours of 9AM-9PM", and "there should not be two inspections within the same 8-hour period", but within whatever constraints were configured for a particular set of inspections, the resulting dates and times should not be predictable.

Unit tests and TDD, IMO, have great value in this system as they can be used to incrementally build it while its full set of requirements is still incomplete, and make sure I'm not "over-engineering" it to do things I don't currently know I need. The strict schedules were a piece-o'-cake to TDD. However, I'm finding it difficult to really define what I'm testing when I write tests for the random portion of the system. I can assert that all times produced by the scheduler must fall within the constraints, but I could implement an algorithm that passes all such tests without the actual times being very "random". In fact that's exactly what's happened; I found an issue where the times, though not predictable exactly, fell into a small subset of the allowable date/time ranges. The algorithm still passed all assertions I felt I could reasonably make, and I could not design an automated test that would fail in that situation, but pass when given "more random" results. I had to demonstrate the problem was solved by restructuring some existing tests to repeat themselves a number of times, and visually check that the times generated fell within the full allowable range.

Does anyone have any tips for designing tests that should expect non-deterministic behavior?

Thanks to all for the suggestions. The main opinion seems to be that I need a deterministic test in order to get deterministic, repeatable, assertable results. Makes sense.

I created a set of "sandbox" tests that contain candidate algorithms for the constraining process (the process by which a byte array that could be any long becomes a long between a min and max). I then run that code through a FOR loop that gives the algorithm several known byte arrays (values from 1 to 10,000,000 just to start) and has the algorithm constrain each to a value between 1009 and 7919 (I'm using prime numbers to ensure an algorithm wouldn't pass by some serendipitous GCF between the input and output ranges). The resulting constrained values are counted and a histogram produced. To "pass", all inputs must be reflected within the histogram (sanity to ensure we didn't "lose" any), and the difference between any two buckets in the histogram cannot be greater than 2 (it should really be <= 1, but stay tuned). The winning algorithm, if any, can be cut and pasted directly into production code and a permanent test put in place for regression.

Here's the code:

```<code>    private void TestConstraintAlgorithm(int min, int max, Func<byte[], long, long, long> constraintAlgorithm)
    {
        var histogram = new int[max-min+1];
        for (int i = 1; i <= 10000000; i++)
        {
            //This is the stand-in for the PRNG; produces a known byte array
            var buffer = BitConverter.GetBytes((long)i);

            long result = constraintAlgorithm(buffer, min, max);

            histogram[result - min]++;
        }

        var minCount = -1;
        var maxCount = -1;
        var total = 0;
        for (int i = 0; i < histogram.Length; i++)
        {
            Console.WriteLine("{0}: {1}".FormatWith(i + min, histogram[i]));
            if (minCount == -1 || minCount > histogram[i])
                minCount = histogram[i];
            if (maxCount == -1 || maxCount < histogram[i])
                maxCount = histogram[i];
            total += histogram[i];
        }

        Assert.AreEqual(10000000, total);
        Assert.LessOrEqual(maxCount - minCount, 2);
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionMSBRejection()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByMSBRejection);
    }

    private long ConstrainByMSBRejection(byte[] buffer, long min, long max)
    {
        //Strip the sign bit (if any) off the most significant byte, before converting to long
        buffer[buffer.Length-1] &= 0x7f;
        var orig = BitConverter.ToInt64(buffer, 0);
        var result = orig;
        //Apply a bitmask to the value, removing the MSB on each loop until it falls in the range.
        var mask = long.MaxValue;
        while (result > max - min)
        {
            mask >>= 1;
            result &= mask;
        }
        result += min;

        return result;
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionLSBRejection()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByLSBRejection);
    }

    private long ConstrainByLSBRejection(byte[] buffer, long min, long max)
    {
        //Strip the sign bit (if any) off the most significant byte, before converting to long
        buffer[buffer.Length - 1] &= 0x7f;
        var orig = BitConverter.ToInt64(buffer, 0);
        var result = orig;

        //Bit-shift the number 1 place to the right until it falls within the range
        while (result > max - min)
            result >>= 1;

        result += min;
        return result;
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionModulus()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByModulo);
    }

    private long ConstrainByModulo(byte[] buffer, long min, long max)
    {
        buffer[buffer.Length - 1] &= 0x7f;
        var result = BitConverter.ToInt64(buffer, 0);

        //Modulo divide the value by the range to produce a value that falls within it.
        result %= max - min + 1;

        result += min;
        return result;
    }
</code>```

... and here's the results:

LSB rejection (bit-shifting the number until it falls within the range) was TERRIBLE, for a very easy-to-explain reason; when you divide any number by 2 until it's less than a maximum, you quit as soon as it is, and for any non-trivial range, that will bias the results towards the upper third (as was seen in the detailed results of the histogram). This was exactly the behavior I saw from the finished dates; all of the times were in the afternoon, on very specific days.

MSB rejection (removing the most significant bit off the number one at a time until it's within the range) is better, but again, because you're chopping off very large numbers with each bit, it's not evenly distributed; you're unlikely to get numbers in the upper and lower ends, so you get a bias toward the middle third. That might benefit someone looking to "normalize" random data into a bell-ish curve, but a sum of two or more smaller random numbers (similar to throwing dice) would give you a more natural curve. For my purposes, it fails.

The only one that passed this test was to constrain by modulo division, which also turned out to be the fastest of the three. Modulo will, by its definition, produce as even a distribution as possible given the available inputs.

答:
Apart from validating that your code doesn't fail, or throws right exceptions in right places you can create a valid input/response pairs (even calculating this manually), feed the input in  the test and make sure it returns expected response. Not great, but that's pretty much all you can do, imho.
However, in your case it's not really random, once you create your schedule you can test for rule conformity - must have 3 inspections per week, between 9-9; there's no real need or ability to test for exact times when inspection occured. </p>

ContentLicense: CC BY-SA 4.0


答:
What you actually want to test here, I assume, is that given a specific set of results from the randomiser, the rest of your method performs correctly.

If that's what you're looking for then mock out the randomiser, to make it deterministic within the realms of the test.

I generally have mock objects for all kinds of non-deterministic or unpredictable (at the time of writing the test) data, including GUID generators and DateTime.Now.

Edit, from comments: You have to mock the PRNG (that term escaped me last night) at the lowest level possible - ie. when it generates the array of bytes, not after you turn those into Int64s. Or even at both levels, so you can test your conversion to an array of Int64 works as intended and then test separately that your conversion to an array of DateTimes works as intended. As Jonathon said, you could just do that by giving it a set seed, or you can give it the array of bytes to return.

I prefer the latter because it won't break if the framework implementation of a PRNG changes. However, one advantage to giving it the seed is that if you find a case in production that didn't work as intended, you only need to have logged one number to be able to replicate it, as opposed to the whole array.

All this said, you must remember that it's called a Pseudo Random Number Generator for a reason. There may be some bias even at that level.

Title: Unit-testing of inherently random/non-deterministic algorithms

Body:
My current project, succinctly, involves the creation of "constrainably-random events". I'm basically generating a schedule of inspections. Some of them are based on strict schedule constraints; you perform an inspection once a week on Friday at 10:00AM. Other inspections are "random"; there are basic configurable requirements such as "an inspection must occur 3 times per week", "the inspection must happen between the hours of 9AM-9PM", and "there should not be two inspections within the same 8-hour period", but within whatever constraints were configured for a particular set of inspections, the resulting dates and times should not be predictable.

Unit tests and TDD, IMO, have great value in this system as they can be used to incrementally build it while its full set of requirements is still incomplete, and make sure I'm not "over-engineering" it to do things I don't currently know I need. The strict schedules were a piece-o'-cake to TDD. However, I'm finding it difficult to really define what I'm testing when I write tests for the random portion of the system. I can assert that all times produced by the scheduler must fall within the constraints, but I could implement an algorithm that passes all such tests without the actual times being very "random". In fact that's exactly what's happened; I found an issue where the times, though not predictable exactly, fell into a small subset of the allowable date/time ranges. The algorithm still passed all assertions I felt I could reasonably make, and I could not design an automated test that would fail in that situation, but pass when given "more random" results. I had to demonstrate the problem was solved by restructuring some existing tests to repeat themselves a number of times, and visually check that the times generated fell within the full allowable range.

Does anyone have any tips for designing tests that should expect non-deterministic behavior?

Thanks to all for the suggestions. The main opinion seems to be that I need a deterministic test in order to get deterministic, repeatable, assertable results. Makes sense.

I created a set of "sandbox" tests that contain candidate algorithms for the constraining process (the process by which a byte array that could be any long becomes a long between a min and max). I then run that code through a FOR loop that gives the algorithm several known byte arrays (values from 1 to 10,000,000 just to start) and has the algorithm constrain each to a value between 1009 and 7919 (I'm using prime numbers to ensure an algorithm wouldn't pass by some serendipitous GCF between the input and output ranges). The resulting constrained values are counted and a histogram produced. To "pass", all inputs must be reflected within the histogram (sanity to ensure we didn't "lose" any), and the difference between any two buckets in the histogram cannot be greater than 2 (it should really be <= 1, but stay tuned). The winning algorithm, if any, can be cut and pasted directly into production code and a permanent test put in place for regression.

Here's the code:

```<code>    private void TestConstraintAlgorithm(int min, int max, Func<byte[], long, long, long> constraintAlgorithm)
    {
        var histogram = new int[max-min+1];
        for (int i = 1; i <= 10000000; i++)
        {
            //This is the stand-in for the PRNG; produces a known byte array
            var buffer = BitConverter.GetBytes((long)i);

            long result = constraintAlgorithm(buffer, min, max);

            histogram[result - min]++;
        }

        var minCount = -1;
        var maxCount = -1;
        var total = 0;
        for (int i = 0; i < histogram.Length; i++)
        {
            Console.WriteLine("{0}: {1}".FormatWith(i + min, histogram[i]));
            if (minCount == -1 || minCount > histogram[i])
                minCount = histogram[i];
            if (maxCount == -1 || maxCount < histogram[i])
                maxCount = histogram[i];
            total += histogram[i];
        }

        Assert.AreEqual(10000000, total);
        Assert.LessOrEqual(maxCount - minCount, 2);
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionMSBRejection()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByMSBRejection);
    }

    private long ConstrainByMSBRejection(byte[] buffer, long min, long max)
    {
        //Strip the sign bit (if any) off the most significant byte, before converting to long
        buffer[buffer.Length-1] &= 0x7f;
        var orig = BitConverter.ToInt64(buffer, 0);
        var result = orig;
        //Apply a bitmask to the value, removing the MSB on each loop until it falls in the range.
        var mask = long.MaxValue;
        while (result > max - min)
        {
            mask >>= 1;
            result &= mask;
        }
        result += min;

        return result;
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionLSBRejection()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByLSBRejection);
    }

    private long ConstrainByLSBRejection(byte[] buffer, long min, long max)
    {
        //Strip the sign bit (if any) off the most significant byte, before converting to long
        buffer[buffer.Length - 1] &= 0x7f;
        var orig = BitConverter.ToInt64(buffer, 0);
        var result = orig;

        //Bit-shift the number 1 place to the right until it falls within the range
        while (result > max - min)
            result >>= 1;

        result += min;
        return result;
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionModulus()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByModulo);
    }

    private long ConstrainByModulo(byte[] buffer, long min, long max)
    {
        buffer[buffer.Length - 1] &= 0x7f;
        var result = BitConverter.ToInt64(buffer, 0);

        //Modulo divide the value by the range to produce a value that falls within it.
        result %= max - min + 1;

        result += min;
        return result;
    }
</code>```

... and here's the results:

LSB rejection (bit-shifting the number until it falls within the range) was TERRIBLE, for a very easy-to-explain reason; when you divide any number by 2 until it's less than a maximum, you quit as soon as it is, and for any non-trivial range, that will bias the results towards the upper third (as was seen in the detailed results of the histogram). This was exactly the behavior I saw from the finished dates; all of the times were in the afternoon, on very specific days.

MSB rejection (removing the most significant bit off the number one at a time until it's within the range) is better, but again, because you're chopping off very large numbers with each bit, it's not evenly distributed; you're unlikely to get numbers in the upper and lower ends, so you get a bias toward the middle third. That might benefit someone looking to "normalize" random data into a bell-ish curve, but a sum of two or more smaller random numbers (similar to throwing dice) would give you a more natural curve. For my purposes, it fails.

The only one that passed this test was to constrain by modulo division, which also turned out to be the fastest of the three. Modulo will, by its definition, produce as even a distribution as possible given the available inputs.


问:
Interesting questions about Behaviour-Driven Development
For my master thesis at Software Engineering, I want to investigate in the new development technique BDD (Behaviour-Driven Development). In my opinion this technique could really improve on customer satisfaction, code coverage and bugs because of the force of executable specifications and the customer-understandable language.

For my thesis however, I struggle with the way I am going to validate that BDD could work better in certain circumstances. At the company I work during my study, work is still mostly done in a traditional, iterative way, where it sometimes is hard to change requirements after the requirements elicitation stage.

My question is, are there any people who already did projects with BDD, what are their experiences and have you ever felt something about BDD that you would want to investigate in, commencing on the above paragraphs? This could help me a lot with constructing my research question. Thanks in advance!

答:
BDD is actually TDD with fixed terminology (see here).

BDD wiki provides a clear explanation. If done right, it can work quite well. At least it worked very well in my team when we switched from almost cowboy coding. The code coverage increased, and with it, the number of bugs reduced, and quality increased.

What is also good about it is that you automatically get YAGNI, KISS and if done right SOLID.

how the output of a new development technique like BDD can be validated?

As other development methods, BDD is not a silver bullet (such thing still doesn't exists in the software development). If after some time you do not see improvements in the code quality, then it's better not to use it. Under code quality, I mean : less bugs, easier to implement change requests, etc.


问:
Adding complexity to remove duplicate code
I have several classes that all inherit from a generic base class. The base class contains a collection of several objects of type T.

Each child class needs to be able to calculate interpolated values from the collection of objects, but since the child classes use different types, the calculation varies a tiny bit from class to class.

So far I have copy/pasted my code from class to class and made minor modifications to each. But now I am trying to remove the duplicated code and replace it with one generic interpolation method in my base class. However that is proving to be very difficult, and all the solutions I have thought of seem way too complex.

I am starting to think the DRY principle does not apply as much in this kind of situation, but that sounds like blasphemy. How much complexity is too much when trying to remove code duplication?

EDIT:

The best solution I can come up with goes something like this:

Base Class:

```<code>protected T GetInterpolated(int frame)
{
    var index = SortedFrames.BinarySearch(frame);
    if (index >= 0)
        return Data[index];

    index = ~index;

    if (index == 0)
        return Data[index];
    if (index >= Data.Count)
        return Data[Data.Count - 1];

    return GetInterpolatedItem(frame, Data[index - 1], Data[index]);
}

protected abstract T GetInterpolatedItem(int frame, T lower, T upper);
</code>```

Child class A:

```<code>public IGpsCoordinate GetInterpolatedCoord(int frame)
{
    ReadData();
    return GetInterpolated(frame);
}

protected override IGpsCoordinate GetInterpolatedItem(int frame, IGpsCoordinate lower, IGpsCoordinate upper)
{
    double ratio = GetInterpolationRatio(frame, lower.Frame, upper.Frame);

    var x = GetInterpolatedValue(lower.X, upper.X, ratio);
    var y = GetInterpolatedValue(lower.Y, upper.Y, ratio);
    var z = GetInterpolatedValue(lower.Z, upper.Z, ratio);

    return new GpsCoordinate(frame, x, y, z);
}
</code>```

Child class B:

```<code>public double GetMph(int frame)
{
    ReadData();
    return GetInterpolated(frame).MilesPerHour;
}

protected override ISpeed GetInterpolatedItem(int frame, ISpeed lower, ISpeed upper)
{
    var ratio = GetInterpolationRatio(frame, lower.Frame, upper.Frame);
    var mph = GetInterpolatedValue(lower.MilesPerHour, upper.MilesPerHour, ratio);
    return new Speed(frame, mph);
}
</code>```

答:
When you say the base class has to perform an algorithm, but the algorithm varies for each sub class, this sounds like a perfect candidate for The Template Pattern.

With this, the base class performs the algorithm, and when it comes the variation for each sub class, it defers to an abstract method which it is the responsibility of the sub class to implement. Think of the way and ASP.NET page defers to your code to implement Page_Load for example.


答:
In my opinion, you are correct, in a sense, that DRY can be taken too far. If two similar pieces of code are likely to evolve in very different directions then you can cause yourself problems by trying not to repeat yourself initially.

However, you are also quite right to be wary of such blasphemous thoughts. Try very hard to think through your options before you decide to leave it alone.

Would it, for example, be better to put that repeated code in a utility class/method, rather than in the base class? See Prefer Composition over Inheritance.

Title: Adding complexity to remove duplicate code

Body:
I have several classes that all inherit from a generic base class. The base class contains a collection of several objects of type T.

Each child class needs to be able to calculate interpolated values from the collection of objects, but since the child classes use different types, the calculation varies a tiny bit from class to class.

So far I have copy/pasted my code from class to class and made minor modifications to each. But now I am trying to remove the duplicated code and replace it with one generic interpolation method in my base class. However that is proving to be very difficult, and all the solutions I have thought of seem way too complex.

I am starting to think the DRY principle does not apply as much in this kind of situation, but that sounds like blasphemy. How much complexity is too much when trying to remove code duplication?

EDIT:

The best solution I can come up with goes something like this:

Base Class:

```<code>protected T GetInterpolated(int frame)
{
    var index = SortedFrames.BinarySearch(frame);
    if (index >= 0)
        return Data[index];

    index = ~index;

    if (index == 0)
        return Data[index];
    if (index >= Data.Count)
        return Data[Data.Count - 1];

    return GetInterpolatedItem(frame, Data[index - 1], Data[index]);
}

protected abstract T GetInterpolatedItem(int frame, T lower, T upper);
</code>```

Child class A:

```<code>public IGpsCoordinate GetInterpolatedCoord(int frame)
{
    ReadData();
    return GetInterpolated(frame);
}

protected override IGpsCoordinate GetInterpolatedItem(int frame, IGpsCoordinate lower, IGpsCoordinate upper)
{
    double ratio = GetInterpolationRatio(frame, lower.Frame, upper.Frame);

    var x = GetInterpolatedValue(lower.X, upper.X, ratio);
    var y = GetInterpolatedValue(lower.Y, upper.Y, ratio);
    var z = GetInterpolatedValue(lower.Z, upper.Z, ratio);

    return new GpsCoordinate(frame, x, y, z);
}
</code>```

Child class B:

```<code>public double GetMph(int frame)
{
    ReadData();
    return GetInterpolated(frame).MilesPerHour;
}

protected override ISpeed GetInterpolatedItem(int frame, ISpeed lower, ISpeed upper)
{
    var ratio = GetInterpolationRatio(frame, lower.Frame, upper.Frame);
    var mph = GetInterpolatedValue(lower.MilesPerHour, upper.MilesPerHour, ratio);
    return new Speed(frame, mph);
}
</code>```


答:
In a way, you answered your own question with that remark in the last paragraph:

I am starting to think the DRY principle does not apply as much in
  this kind of situation, but that sounds like blasphemy.

Whenever you find some practice not really practical for solving your problem, don't try to use that practice religiously (word blasphemy is kind of a warning for this). Most practices have their whens and whys and even if they cover 99% of all the possible cases, there's still that 1% where you may need a different approach.

Specifically, with regard to DRY , I also found that sometimes it is actually better to even have several pieces of duplicated but simple code than one giant monstrosity that makes you feel sick when you look at it.

That being said, existence of these edge cases should not be used as an excuse for sloppy copy&paste coding or complete lack of reusable modules. Simply, if you have no idea how to write a both generic and readable code for some problem in some language, then it's probably less bad to have some redundancy. Think of whoever has to maintain code. Would they more easily live with redundancy or obfuscation?

A more specific advice about your particular example. You said that these calculations were similar yet slightly different. You might want to try breaking up your calculation formula to smaller subformulas and then have all your slightly different calculations call these helper functions to do the sub calculations. You'd avoid the situation where every calculation depends on some over-generalized code and you'd still have some level of reuse.


答:
Sounds like your "one generic interpolation method" in each class is doing too much and should be made into smaller methods.

Depending on how complex your calculation is, why couldn't each "piece" of the calculation be a virtual method like this

```<code>Public Class Fraction
{
     public virtual Decimal GetNumerator(params?)
     public virtual Decimal GetDenominator(params?)
     //Some concrete method to actually compute GetNumerator / GetDenominator
}
</code>```

And override the individual pieces when you need to make that "slight variation" in the calculation's logic.

(This is a very tiny and useless example of how you could add a lot of functionality while overriding small methods)

Body:
Sounds like your "one generic interpolation method" in each class is doing too much and should be made into smaller methods.

Depending on how complex your calculation is, why couldn't each "piece" of the calculation be a virtual method like this

Public Class Fraction
{
     public virtual Decimal GetNumerator(params?)
     public virtual Decimal GetDenominator(params?)
     //Some concrete method to actually compute GetNumerator / GetDenominator
}

And override the individual pieces when you need to make that "slight variation" in the calculation's logic.

(This is a very tiny and useless example of how you could add a lot of functionality while overriding small methods)


问:
C programming in Windows 7
Which is the best book and what are the best tools for C programming in Windows 7?

Would using C in any way hinder me when it comes to using the Windows API as opposed to using C++ or C#? I would like to use C, because it seems to me that object-oriented programming is bad for performance and the abstraction seems only counter-productive if the right people are doing the programming. I will mostly do GUIs and background services that do a lot of networking, possibly at OSI Layer 2, and public key + cascaded symmetric key cryptograpy.

Also, the core of the programs (excluding any that deal directly with OSI Layer 2) should be portable to Android.

答:
Given that the entire Win 32 API is exposed primarily as C functions, there' no hinderance to using C, other than maybe the lack of libraries.

The best book to start with is probably still Programming Windows by Charles Petzold.  It's showing its age, but the basics haven't changed, and all the new stuff can be learned best through MSDN's online reference - which is where you should go once you've gotten started anyway.

The best environment for C under windows is usually Visual Studio.  You can use the express c++ version if you don't want to pay for the bigger versions.  Just use the /TC switch to compile as C code rather than C++.  It does lack some of the newer C features, but it's a solid compiler that works well with Windows.

As to your editorial on C vs C++ programming, it "seems to me" like you're jumping the gun in assuming any performance gains / losses between object-oriented and procedural programming.

Title: C programming in Windows 7


答:
DRY is a guideline to follow, not an unbreakable rule. At some point you need to decide that its not worth having X levels of inheritance and Y templates in every class you are using just to say there is no repetition in this code. A couple good questions to ask would be will it take me longer to extract these similar methods and implement them as one, then it would to search through all of them should the need to change arise or is their potential for a change to occur that would undo my work extracting these methods in the first place? Am I at the point where additional abstraction is starting to make understand where or what this code does is a challenge?

If you can answer yes to either of those questions then you have a strong case for leaving potentially duplicated code


答:
child classes use different types, the calculation varies a tiny bit from class to class.

First and foremost thing is: First clearly identify what part is changing and what part is NOT changing between the classes. Once you've identified that, your problem is solved.

Do that as the first exercise before starting the re-factoring. Everything else will fall in place automatically after that.


问:
Can I use Node to add email functionality to an existing site?
I have a client with an existing straight up HTML/JavaScript site. No back end of any kind. He wants to add email functionality to it and I was thinking of using Node to do this for two reasons:

It seems like an extremely lightweight way to do it

He's talking about adding further functionality in the future.

What are the positives and negatives of this approach?

答:
I gues you could use the emailjs plugin for node. Even if node wasn't serving the site you could still interact with node from the static webpage through websockets using socket.io.

This all sounds a bit complicated but having been playing with node in the last week this stuff is amazingly easy to accomplish.


答:
what you can unit test is the logic determine if the random dates are valid or if another random date needs to be selected.

There is no way to test a random date generator short of getting a bunch of dates and deciding if they are suitably random.


答:
Positive: Node is really cool and you'll feel really cool writing the code.

Negative: The appropriate solution would take 1/10th the time in PHP, Perl, or Python and one of those languages is probably already installed on the server. In addition, Node is still in beta.

Title: Can I use Node to add email functionality to an existing site?

Body:
I have a client with an existing straight up HTML/JavaScript site. No back end of any kind. He wants to add email functionality to it and I was thinking of using Node to do this for two reasons:

It seems like an extremely lightweight way to do it

He's talking about adding further functionality in the future.

What are the positives and negatives of this approach?


答:
I believe that almost all repetition of more than a couple lines of code can be factored out in some way or another, and almost always should be.

However, this refactoring is easier in some languages than others.  It is quite easy in languages like LISP, Ruby, Python, Groovy, Javascript, Lua, etc.  Usually not too difficult in C++ using templates.  More painful in C, where the only tool may be preprocessor macros.  Often painful in Java, and sometimes simply impossible, e.g. trying to write generic code to handle multiple built-in numeric types.

In more expressive languages, there is no question: refactor anything more than a couple of lines of code.  With less expressive languages you have to balance the pain of the refactoring against the length and stability of the repeated code.  If the repeated code is long, or liable to change frequently, I tend to refactor even if the resulting code is somewhat difficult to read.

I will accept repeated code only if it is short, stable, and refactoring is just too ugly.  Basically I factor out almost all duplication unless I am writing Java.

It's impossible to give a specific recommendation for your case because you haven't posted the code, or even indicated which language you are using.


答:
First understand that Behavior Driven Development (BDD) does not equal executable specifications in customer language.

Behavior driven development is equal to test driven development (TDD) in behavioral language.

TDD/BDD can yield great benefits to design, code quality, etc, if done pragmatically by BDD experienced developers.

Executable requirements can also yield benefits, but this depends more on your relationship with your customer, the nature of the product, and the organization.

Title: Interesting questions about Behaviour-Driven Development

Body:
For my master thesis at Software Engineering, I want to investigate in the new development technique BDD (Behaviour-Driven Development). In my opinion this technique could really improve on customer satisfaction, code coverage and bugs because of the force of executable specifications and the customer-understandable language.

For my thesis however, I struggle with the way I am going to validate that BDD could work better in certain circumstances. At the company I work during my study, work is still mostly done in a traditional, iterative way, where it sometimes is hard to change requirements after the requirements elicitation stage.

My question is, are there any people who already did projects with BDD, what are their experiences and have you ever felt something about BDD that you would want to investigate in, commencing on the above paragraphs? This could help me a lot with constructing my research question. Thanks in advance!


问:
Advantages of Scrum for the developers themselves?
Scrum being a project management methodology, how would you 'sell' it to the developers in a team that is reasonably happy with its current situation?

It seems easy to me to explain to our Product Manager how Scrum will allow him to get regular releases, to amend requirements, and get the team to focus on the high-priority stories first.  I found it easy to explain what TDD or Continuous Integration bring in a developer's day-to-day life.

But how can developers be convinced to embrace Scrum?  How would Scrum make their life easier?

答:
Scrum will provide much more visibility on what is going on. Bad management, last minute changes, pressures, and all kind of stuff a developer usually face.

However, it will also bring a lot of visibility on procrastinators, bad faith developers, insane individualists, ... in other words, bad developers.

Scrum is a double edged sword

Scrum will bring you with opportunities to solve those problems. That's why it's so powerful.


问:
How do you normally layout a class's regions?
I was wondering if there was a standard for laying out a class's regions.

I currently use

```<code>Fields
Constructor
Properties
Public Methods
Private Methods
</code>```

Fields being Private Properties and Properties being the public ones. I'll normally use subregions within that if needed, or will occasionally add other regions below (such as interface or baseClass members).

答:
Like Wyatt and a couple other answers, I also generally avoid the use of regions. Regions have one purpose; to hide code you don't want to have to look at. If you have a lot of code in a class you don't want to have to look at, and thus you need a lot of regions to allow you to collapse said code, then you probably have too much code in the class. ReSharper doesn't respect regions when deciding where to place new code, unless it created the region (which it does for interface implementations).

The one use of regions that I find acceptable is to hide "unavoidably ugly" code; code which deals with specific implementation details that can't be well-architected internally to current standards. This is usually advanced, esoteric code that should generally not be messed with by the average junior programmer once written. These are things like:

Certain built-in interface implementations (IDisposable, IConvertible, sometimes IEnumerable or IComparable as they require generic and non-generic implementations)

Embedded P/Invoke externs and related structures.

Finalizers/destructors (usually goes with IDisposable)

Hooks to unmanaged memory/pointers/"unsafe" code.


答:
This is going to sound like a stupid answer, but I'm going to throw it out there because this is how I've seen it done before:

Decouple your code from the PRNG - pass the randomization seed into all of the code that uses randomization. Then you can determine the 'working' values from a single seed (or multiple seeds of that would make you feel better). This will give you the ability to adequately test your code without having to rely on the law of large numbers.

It sounds inane, but this is how the military does it (either that or they use a 'random table' that isn't really random at all)


答: There's really no better way than running it a bunch of times and seeing if you get the distribution you want.  If you have 50 allowed potential inspection schedules, you run the test 500 times and make sure each schedule is used close to 10 times.  You can control your random generator seeds to make it more deterministic, but that will also make your tests more tightly coupled to the implementation details.</p>


问:
Is there a difference between casting and converting types in imperative programming languages?
The question came up in a discussion at StackOverflow.

Is there a clean distinction between the two concepts cast and convert (concerning the type of an object), or are these two words describing exactly the same? How about languages other than C++, Python and Java? EDIT: What if the types in question are primitive types, like int to float?

答:
Theoretically speaking, the two concepts are vastly different:

Type Casting refers to exchanging one type (roughly speaking, an object structure) for another while Type Conversion refers to translating of values (roughly speaking, contents of the object), so that they may be interpreted as belonging to a new type. Theoretically, they never mix.

That said, practically speaking, while you can have one without another, it's, almost always, a bad idea. It rarely makes sense to change your perception of an objects' structure, without also altering its contents. Practically, they're almost always the same


答:
While casting, you read the instance of one class as if it is the instance of another class. It could be appliccable for this pair of classes or not. No runtime work except checking. Often the possible incompatibility could be caught on compiling stage.

While converting, you recombine or recount fields of an instance of one class into an instance of another class. If there is a function for it, it could be applicable or not for this very instance. All the work is done during runtime. No error could be checked while compiling.

Title: Is there a difference between casting and converting types in imperative programming languages?

Body:
The question came up in a discussion at StackOverflow.

Is there a clean distinction between the two concepts cast and convert (concerning the type of an object), or are these two words describing exactly the same? How about languages other than C++, Python and Java? EDIT: What if the types in question are primitive types, like int to float?


问:
Is it possible to compile Java into machine code? (Not bytecode)
Can you have Java compiled straight into machine code?

I want to do this so I have control over what platforms it's used on, and don't know C,C++ etc.

答:
Not quite directly answering the OP, but an perhaps an interesting aside.  Java can be run in three modes:

Mixed (default) - A combination of Interpreted and Machine compiled code (machine compiled == compiled by JIT at runtime)

With -Xint flag - Interpreted - Byte code only

With -Xcomp flag - Compiled - machine compiled


答:
You might want to take a look at Sevcikova et al:
"Automated Testing of Stochastic Systems: A Statistically Grounded Approach" (PDF).

The methodology is implemented in various test cases for the UrbanSim simulation platform.


问:
Create Primary Interop Assemblies or generate them?
I've never seen this question answered definitively:

If you are maintaining a COM DLL that can be used by a .NET program, is it best to:

Import the COM DLL into each project, which generates an Interop assembly for each project? or

Generate the Primary Interop Assembly with TLBIMP every time the COM DLL is compiled? or

Write the Primary Interop Assembly in C# and compile that every time the COM DLL is compiled?

I would like to do either number 2 or number 3. Number 2 sounds compelling, but I cannot see how you set the AssemblyTitleAttribute (and other such attributes); I would assume you use custom attributes in the IDL which TLBIMP would pick up.

答:
In one of my projects, we implemented option 2. The generation involved creating the assembly, disassembling it using ildasm, reassembling it back using ilasm and finally signing it. The reason for the roundtrip was that we wanted to embed version information into the PIA.

AFAIK, option 1 won't allow exchanging COM objects between different applications.

Option 3 surely gives you the full power of designing the interop "the way it should be", not the way it is spat out by tlbimp. Writing simple forwarders is not that hard, but tlbimp does this job quite well already. If you really want it "the way it should be", the interop may very well become a complex project in its own right.


答:
Different languages define the words "cast" and "convert" differently; I don't think the question is meaningful other than in reference to a particular language.

In C, for example, the term "cast" properly refers only to an explicit cast operator, consisting of a type name in parentheses preceding the expression to be converted.  A "conversion" converts a value of one type to a value of another type; some conversions are implemented by re-interpreting the bits that make up the representation, but it's defined as a value-to-value conversion.  (Yes, that's true even for pointer conversions; it's possible for different pointer types to have different representations.)

Note that there is no such thing as an "implicit cast" in C.

Some conversions are explicit, specified by a cast operator.  Others are implicit, and are applied in certain cases when an expression of one type is used in a context that needs an expression of a different type.  The conversion performed is exactly the same in either case.

For example:

```<code>double x = 1.23;
int y = (int)x;  /* A cast, or explicit conversion, setting y to 1 */
int z = x;       /* An implicit conversion, setting z to 1. */
</code>```

C++ is similar; it has the same casts and conversions as C, and it adds a functional notation equivalent to a C-style cast expression, plus 4 more specific keywords: const_cast, dynamic_cast, reinterpret_cast, and static_cast.

Body:
Different languages define the words "cast" and "convert" differently; I don't think the question is meaningful other than in reference to a particular language.

In C, for example, the term "cast" properly refers only to an explicit cast operator, consisting of a type name in parentheses preceding the expression to be converted.  A "conversion" converts a value of one type to a value of another type; some conversions are implemented by re-interpreting the bits that make up the representation, but it's defined as a value-to-value conversion.  (Yes, that's true even for pointer conversions; it's possible for different pointer types to have different representations.)

Note that there is no such thing as an "implicit cast" in C.

Some conversions are explicit, specified by a cast operator.  Others are implicit, and are applied in certain cases when an expression of one type is used in a context that needs an expression of a different type.  The conversion performed is exactly the same in either case.

For example:

double x = 1.23;
int y = (int)x;  /* A cast, or explicit conversion, setting y to 1 */
int z = x;       /* An implicit conversion, setting z to 1. */

C++ is similar; it has the same casts and conversions as C, and it adds a functional notation equivalent to a C-style cast expression, plus 4 more specific keywords: const_cast, dynamic_cast, reinterpret_cast, and static_cast.