问:
Should I continue my self-taught coding practice or learn how to do coding professionally?
Lately I've been getting professional work, hanging out with other programmers, and making friends in the industry. The only thing is I'm 100% self-taught. It's caused my style to extremely deviate from the style of those that are properly trained. It's the techniques and organization of my code that's different.

It's a mixture of several things I do. I tend to blend several programming paradigms together. Like Functional and OO. I lean to the Functional side more than OO, but I see the use of OO when something would make more sense as an abstract entity. Like a game object. Next I also go the simple route when doing something. When in contrast, it seems like sometimes the code I see from professional programmers is complicated for the sake of it! I use lots of closures. And lastly, I'm not the best commenter. I find it easier just to read through my code than reading the comment. And most cases I just end up reading the code even if there are comments. Plus I've been told that, because of how simply I write my code, it's very easy to read it.

I hear professionally trained programmers go on and on about things like unit tests. Something I've never used before so I haven't even the faintest idea of what they are or how they work. Lots and lots of underscores "_", which aren't really my taste. Most of the techniques I use are straight from me, or a few books I've read. Don't know anything about MVC, I've heard a lot about it though with things like backbone.js. I think it's a way to organize an application. It just confuses me though because by now I've made my own organizational structures.

It's a bit of a pain. I can't use template applications at all when learning something new like with Ubuntu's Quickly. I have trouble understanding code that I can tell is from someone trained. Complete OO programming really leaves a bad taste in my mouth, yet that seems to be what EVERYONE else is strictly using.

It's left me not that confident in the look of my code, or wondering whether I'll cause sparks when joining a company or maybe contributing to open source projects. In fact I'm rather scared of the fact that people will eventually be checking out my code. Is this just something normal any programmer goes through or should I really look to change up my techniques?

答:
In fact I'm rather scared of the fact that people will eventually be
  checking out my code. Is this just something normal any programmer
  goes through or should I really look to change up my techniques?

How would you know what to change without some feedback from more experienced programmers?

Having other people review your work can be daunting, especially the first few times, but it's the best way to get the constructive criticism that you need to improve your skills. There's a SE site for code reviews that you may find helpful. Asking smart friends to look at your code is another good way to get some feedback.


问:
Is it any good to use binary arithmetic in a C++ code like "C style"?
I like the fact that the C language lets you use binary arithmetic in an explicit way in your code, sometimes the use of the binary arithmetic can also give you a little edge in terms of performance; but since I started studying C++ i can't really tell how much i have seen the explicit use of something like that in a C++ code, something like a pointer to pointer structure or an instruction for jumping to a specific index value through the binary arithmetic.

Is the binary arithmetic still important and relevant in the C++ world?
How i can optimize my arithmetic and/or an access to a specific index?
What about the C++ and the way in which the bits are arranged according to the standard?

... or i have taken a look at the wrong coding conventions ... ?

答:
Follow these steps:

Write the code as simple and clear as possible.

Turn on all compiler optimizations.

Consider whether you have sufficient knowledge about the specific target CPU and its instruction set (assembler). If not, then you will probably have a hard time to do any manual optimizations and should probably not attempt it, as you will likely just end up obfuscating the code for no gain. Also note that manual optimization is only necessary if your compiler has poor support for the specific target platform. As an alternative, you could try another compiler.

Identify performance bottlenecks. How to find them depends on the target system. In "high-level" programs such as desktop programming, you benchmark your code through specific tools designed for that purpose, or through OS API functions. On "low-level" programs such as embedded systems, you typically use an oscilloscope to measure realtime performance. On any program, you can disassemble the code and see what the compiler actually came up with.

If there are no bottlenecks that affects your program's performance, you don't need to do a thing and you can stop reading here.

If there are bottlenecks that have impact on your program, you may need to perform manual optimization.

How do manual optimizations depends on the target CPU, there is no universal trick. Common things to look for are: floating point arithmetic, alignment, integer sizes, division, branch prediction & instruction cache handling, use of needlessly complex library functions... and so on.

ContentLicense: CC BY-SA 3.0


问:
Moving from mock to real objects?
I'm like doing TDD so I started everything mocking objects, creating interface, stubbing, great.

The design seems to work, now I'll implement the stuff, a lot of the code used in the stubs are going to be reused in my real implementation yay!

Now should I duplicate the tests to use the real object implementation (but keeping the mocks object of the sensitive stuff like Database and "services" that are out of my context (http calls, etc...)) Or just change the mocks and stubs of the actual tests to use the real objects.......

So the question is that, keep two tests or replace the stubs, mocks?

And after that, I should keep designing with the mocks, stubs or just go with real objects?

(Just making myself clear I'll keep the mock object of the sensitive stuff like database and services that are out of my context, in both situations.)

EDIT

[Fact]
public void Change_status()
{
    var dbContext = MockRepository.GenerateStub<IDbContext>();
    var repository = MockRepository.GenerateMock<IRepository<Foo>>();

    var predicate = MockRepository.GenerateStub<Func<Foo, bool>>();
    repository.Expect(x => x.Get(predicate)).Return(_foo).Repeat.Once();
    dbContext.Expect(x => x.Commit());

    var ctl = MockRepository.GenerateStub<IFooCtl>();
    ctl.Stub(x => x.RejectRequest(_fooView)).WhenCalled(delegate
    {
        var foo = repository.Get(predicate);
        foo.Status = Status.Rejected;
        _fooView.Status = Status.Rejected.ToString();

    }).Return(true);

    ctl.RejectRequest(_fooView);

    repository.VerifyAllExpectations();
    dbContext.VerifyAllExpectations();
    Assert.True(_fooView.Status == "Rejected");
    Assert.True(result.Count() == 1);
}
```

<p>This is a test, where I mock the repository, context and stub the facade. So what I'm trying to say is if I should change the stub of the facade to use the "real" code so this should be tested as</p>

<pre class="lang-csh prettyprint-override"><code>[Fact]
public void Change_status()
{
    var dbContext = MockRepository.GenerateStub<IDbContext>();
    var repository = MockRepository.GenerateMock<IRepository<Foo>>();

    var predicate = MockRepository.GenerateStub<Func<Foo, bool>>();
    repository.Expect(x => x.Get(predicate)).Return(_foo).Repeat.Once();
    dbContext.Expect(x => x.Commit());

    var ctl = new FooCtl(loanRepository, happyLoanDbContext);
    var result = ctl.RejectRequest(_loanView);

    repository.VerifyAllExpectations();
    dbContext.VerifyAllExpectations();
    Assert.True(_result);
}
</code>```

Or if I should leave everything mocking and stubbing that tests the designs and create new ones that tests the implementation.

EDIT

Thanks for all your answer, I think I understand it better, I must know which is my SUT and test that, no mock or stub the SUT just the components that will help the SUT to pass the test

答:
Or if I should leave everything mocking and stubbing that tests the
  designs and create new ones that tests the implementation.

A unit test never tests abstractions, or designs as you put it. It always tests one concrete implementation, that of the class under test.

In other words, if you have a test fixture for class A where you mock or stub out A's dependencies B and C, then you're not testing B and C's behavior or design. You're only testing A's behavior and that it is able to talk to B and C properly. In order to test concrete implementations of B and C, you have to create dedicated tests fixtures for both of them.

From a purely isolated unit test perspective, you neither need to substitute mocks for real implementations afterwards, nor to create integration test counterparts besides your unit tests (integration tests = tests involving several concrete implementations at the same time). Your isolated unit tests should stay as they are, with all the mocks and stubs. They stand on their own provided that you test all concrete implementations and their interactions with their dependencies.

As Erik points out, you could create integration tests, but keep in mind that they come at a cost, both in terms of processing time and maintenance time, and they shouldn't replace unit tests as your primary test harness IMO.

Title: Moving from mock to real objects?


问:
Should you keep a copy of all the code you write?
I know the company you work for owns the code and obviously you will get arrested if you try to sell it. But is it uncommon for developers to keep a personal copy of the code they wrote (for future reference)?

Apparently this guy was sent to prison for copying source code.

答:
I haven't yet kept any code that I've done for employers. Freelance stuff I've kept (it can be hard to support a client if I lose my code).

However, I'm considering keeping the code that I have made for this employer. The reason is that I'm a web developer, and I've developed a lot of client-side things that look rather pretty. I didn't design them, but I implemented them and often came up with the idea.
I would like to keep a copy of this stuff to build an online portfolio. As we all know, sites don't last forever, so I can't realistically count on my work staying online. Having a backup copy would allow me to have a portfolio online.

I know that designers often keep copies of their work (even if it was work for hire) for portfolio purposes.

I'm not sure what the legality of this is (it is not explicitly mentioned in my contract).


问:
What do you consider to be the prime cause of software defects (and how to minimize them)
I define defect as :

"something within the application design or code which prevents it functioning as per requirements."

I'm looking for ideas about the causes of defects, eg the human factor, lack of testing, lack of prototyping, and possible ideas to mitigate these.

答:
The prime cause of software defects is writing code.

Write less code and you'll have fewer bugs ;-)

ContentLicense: CC BY-SA 2.5


问:
Evolution of an Application: how to manage and improve core engine?
The web application I work on has been live for a year now, but it's time for it to evolve and one of the ways in which it is evolving is into a multi-brand application - in this case several different companies using the application, different templates/content and some slight business logic changes between them.

The problem I'm facing is implementing a best practice across the site where there are differences in business logic for each brand. These will mostly be very superficial, using a an alternative mailing list provider or capturing some extra data in a form.

I don't want to have if(brand === x) { ... } else { ... } all over the site especially as most of what needs to be changed can be handled with extending the existing class.

I've thought of several methods that could be used to instantiate the correct class, but I'm just not sure which is going to be best especially as some seem to lead to duplication of more code than should be necessary.

Here's what I've considered:

1) Use a Static Loader similar to Zend_Loader which can take the class being requested, and has knowledge of the Brand and can then return the correct object.

```<code>$class = App_Loader::getObject('User', $brand);
</code>```

2) Factory classes. We use these in the application already for Products but we could utilise them here also to provide a transparent interface to the class.

3) Routing the page request to a specific brand controller. This however seems like it would duplicate a lot of code/logic.

Is there a pattern or something else I should be considering to solve this problem?

4) How to manage a growing project that has multiple custom instances in production?

Update
This is a PHP application so the decisions on which class to load are made per request. There could be upwards of 100+ different 'brands' running.

答:
I would be storing different configuration options in a database and writing a configuration application.

This way you can load the configuration by "brand". Any new functionality which is brand sepcific can be configured on future brand sites, without modifying code.

if (brand=="x") is essentially hard coding, avoid it, you would be better to code something like if (configObject.IsFeatureSwitchedOn)

EDIT: You are thinking of having one deployed instance running multiple brands? Don't do it, it will be a maintenance and scalability nightmare.


答:
Question is - How to manage a growing project that has multiple instances customized and in production with some customization in core project? Answer is - through custom configuration process build into your core project.

Here you are some configuration suggestions from MSDN - Managing Configuration Options. This can be used as an idea how to configure your so called "multi-brand" project.

You may also need to plan a strategy for deployment of custom projects that have sharing core functionality: Here is an example for .NET platform which might be used as an idea. MSDN - Project Configuration for Managing Deployment

Title: Evolution of an Application: how to manage and improve core engine?

Body:
The web application I work on has been live for a year now, but it's time for it to evolve and one of the ways in which it is evolving is into a multi-brand application - in this case several different companies using the application, different templates/content and some slight business logic changes between them.

The problem I'm facing is implementing a best practice across the site where there are differences in business logic for each brand. These will mostly be very superficial, using a an alternative mailing list provider or capturing some extra data in a form.

I don't want to have if(brand === x) { ... } else { ... } all over the site especially as most of what needs to be changed can be handled with extending the existing class.

I've thought of several methods that could be used to instantiate the correct class, but I'm just not sure which is going to be best especially as some seem to lead to duplication of more code than should be necessary.

Here's what I've considered:

1) Use a Static Loader similar to Zend_Loader which can take the class being requested, and has knowledge of the Brand and can then return the correct object.

```<code>$class = App_Loader::getObject('User', $brand);
</code>```

2) Factory classes. We use these in the application already for Products but we could utilise them here also to provide a transparent interface to the class.

3) Routing the page request to a specific brand controller. This however seems like it would duplicate a lot of code/logic.

Is there a pattern or something else I should be considering to solve this problem?

4) How to manage a growing project that has multiple custom instances in production?

Update
This is a PHP application so the decisions on which class to load are made per request. There could be upwards of 100+ different 'brands' running.


答:
First my experience with what another company has done before: They had exactly the same live code used by several of their clients, with just skin changes, and lots of conditional logic behind. It meant that if one of their clients went down because there was a bug in the code that was just promoted, every single of their clients went down. So have that in mind. You want to have separate deployments (one would think that is the common sense thing to do)

I'm wondering if the easiest thing to do is to implement Strategy patterns whenever you have to do something different. Then, as the number of strategies grow, you can consolidate them together in a class, with subclasses for each different brand, that are initialize by a factory.


答:
I've done this in the past a few jobs ago.

However I've never once gone back and looked at it. I've occasionally reused ideas and things I learned but I've not once found a reason to go back and look at the code.

So I wouldn't bother any more. It's legally dubious, and I've never actually found it useful in practice.

Title: Should you keep a copy of all the code you write?

Body:
I know the company you work for owns the code and obviously you will get arrested if you try to sell it. But is it uncommon for developers to keep a personal copy of the code they wrote (for future reference)?

Apparently this guy was sent to prison for copying source code.


问:
C Flexible Arrays: When did they become part of the standard?
I learned to program in C many years ago, and used C steadily for about 10 years.

These days, I occasionally have to look at C code, because our Informix 4GL RDS customized runners also contain C code, but it is fairly simplistic code.

When I was using C a lot, I never remember hearing about of flexible arrays. I am asking this question, because I came across this SO question. Thanks.

答:
There are two different things that the C99 standard added and they are easy to mix up by mistake:

Flexible array members. This means that a struct can have a member of unknown size at the end. Example from the C standard:

```<code>struct s { int n; double d[]; };

int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));
</code>```

This was used before C99 as well, but it was then undefined behavior, known as the "struct hack" referred to in another answer. Before C90, there could be unexpected padding bytes  at the end of the struct, leading to bugs.

Variable length arrays (VLA). These are arrays with their size set in runtime. They are most likely implemented by the compiler by using dynamic memory allocation. Example:

```<code>void func (int n)
{
  int array[n];
}
</code>```

Body:
There are two different things that the C99 standard added and they are easy to mix up by mistake:

Flexible array members. This means that a struct can have a member of unknown size at the end. Example from the C standard:

struct s { int n; double d[]; };

int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

This was used before C99 as well, but it was then undefined behavior, known as the "struct hack" referred to in another answer. Before C90, there could be unexpected padding bytes  at the end of the struct, leading to bugs.

Variable length arrays (VLA). These are arrays with their size set in runtime. They are most likely implemented by the compiler by using dynamic memory allocation. Example:

void func (int n)
{
  int array[n];
}


答:
I think either of your first two suggestions should do the trick.  The third option will result in too much duplication which increases your risk for code defects to slip into the production stream.

At a broader level, the first two options are essentially the same logical path and the difference is where they execute.  You and your peers are in the best position to determine the least disruptive means for inserting the change.

If you haven't done so already, having a common config module will streamline some of the changes you're suggesting. Apologies in advance for suggesting the obvious but I wanted to make sure it was brought up.

If you haven't already, map out the various use cases that you're likely to see.  It will give you a framework to refer back to when thinking through the design and test cases to generate.  As others have pointed out - more common code means an increased risk of disabling many client sites from one bug.  Automated regression / stability testing are going to help with mitigating that risk.  Ditto with dev / test / prod environments, but I'm assuming you already have that in place.


问:
How should I implement Transaction database EJB 3.0
In the CustomerTransactions entity, I have the following field to record what the customer bought:

```<code>@ManyToMany
private List<Item> listOfItemsBought;
</code>```

When I think more about this field, there's a chance it may not work because merchants are allowed to change item's information (e.g. price, discount, etc...). Hence, this field will not be able to record what the customer actually bought when the transaction occurred.

At the moment, I can only think of 2 ways to make it work.

I will record the transaction details into a String field. I feel that this way would be messy if I need to extract some information about the transaction later on.

Whenever the merchant changes an item's information, I will not update directly to that item's fields. Instead, I will create another new item with all the new information and keep the old item untouched. I feel that this way is better because I can easily extract information about the transaction later on. However, the bad side is that my Item table may contain a lot of rows.

I'd be very grateful if someone could give me an advice on how I should tackle this problem.

UPDATE: I'd like to add more information about the current design.

```<code>public class Customer implements Serializable {
    @OneToMany
    private List<CustomerTransactions> listOfTransactions;
}

public class CustomerTransactions implements Serializable {
    @ManyToMany
    private List<Item> listOfItemsBought;
}

public class Merchant implements Serializable {
    @OneToMany
    private List<Item> listOfSellingItems;
}
</code>```

答:
javax.ejb.TransactionAttribute annotation (@TransactionAttribute) can be applied to a bean class or it's methods

```<code>public class Customer implements Serializable {
    @OneToMany
    private List<CustomerTransactions> listOfTransactions;
}

public class CustomerTransactions implements Serializable {
    @ManyToMany
    private List<Item> listOfItemsBought;
}

public class Merchant implements Serializable {
    @OneToMany
    private List<Item> listOfSellingItems;
}
</code>```

Example:

```<code>@Transactional(readOnly = false, propagation=Propagation.SUPPORTS)
public long insertTrade(TradeData trade) throws Exception {
   //JDBC Code...
}

@Transactional(readOnly = false, propagation=Propagation.REQUIRED)
public long insertTrade(TradeData trade) throws Exception {
   //JDBC code...
}

@Transactional(readOnly = true)
public TradeData getTrade(long tradeId) throws Exception {
   return em.find(TradeData.class, tradeId);
}

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public TradeData placeTrade(TradeData trade) throws Exception {
   try {
      insertTrade(trade);
      updateAcct(trade);
      return trade;
   } catch (Exception up) {
      //log the error
      throw up;
   }
}
</code>```

OwnerDisplayName: JamesBoyZ

Body:
javax.ejb.TransactionAttribute annotation (@TransactionAttribute) can be applied to a bean class or it's methods

public class Customer implements Serializable {
    @OneToMany
    private List<CustomerTransactions> listOfTransactions;
}

public class CustomerTransactions implements Serializable {
    @ManyToMany
    private List<Item> listOfItemsBought;
}

public class Merchant implements Serializable {
    @OneToMany
    private List<Item> listOfSellingItems;
}

Example:

@Transactional(readOnly = false, propagation=Propagation.SUPPORTS)
public long insertTrade(TradeData trade) throws Exception {
   //JDBC Code...
}

@Transactional(readOnly = false, propagation=Propagation.REQUIRED)
public long insertTrade(TradeData trade) throws Exception {
   //JDBC code...
}

@Transactional(readOnly = true)
public TradeData getTrade(long tradeId) throws Exception {
   return em.find(TradeData.class, tradeId);
}

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public TradeData placeTrade(TradeData trade) throws Exception {
   try {
      insertTrade(trade);
      updateAcct(trade);
      return trade;
   } catch (Exception up) {
      //log the error
      throw up;
   }
}


问:
Any suggested approaches to track bugs/defects?
What is the best way to track defect sources in tfs?

We have various teams for a project like the vulnerability team, the customer, pre-sales, etc. We give a build and these teams independently test it. They do not have access to our tfs system. So they usually send in their defects via email. It will usually be send in an excel format. Our testing team takes these up and logs them into tfs.

Sometimes they modify the original defect description (in excel) and add the expected/actual results. Sometimes they miss to cite the source. I am talking about managing the various sources as such.

Is there a way we can add these sources into tfs, and actually link this particular source with the defects, with individual comments associated with them (saying where in the source we can find the actual material for the defect).

Edit:

I don't know if there is a way to manage various sources. Consider this: the vulnerability assessment team has come out with defects/suggestions. They captured it into an excel and passed that on to the testing team (in my case). The testing team takes the responsibility of elaborating the defect and logging it in tfs. Now say that the excel has come with 20 defect items. This is my source. (It answers the question where did this defect come from). So ultimately when I am looking at a bug I know from where it came from - I'll ultimately be looking at the email sent from the VA team which has the excel or the excel file itself sent by the VA team.

It may be one of the 20 items in that excel. How should the tester link to this source just once? On the contrary, it does not make sense for the tester to attach the same excel 20 times (i.e. attach the same excel for the 20 defects while logging it into tfs) right? I hope you get my point.

答:
There are number of ways to track bugs in TFS, depending on your version and needs.
Here you are some resources for thought:

How to: Track Your Bugs

How to: Verify a Bug is Fixed Using Microsoft Test Manager

TFS 2010 Project Management - bug tracking section

Tracking Bugs, Tasks, and Other Work Items

If you are using TFS2008, this post might help: Bug tracking with TFS 2008

ContentLicense: CC BY-SA 4.0


答: Your "real" classes might look like mocks now, but in the future they could change drastically.  Do you really want future changes in your real classes to have an effect on other unit tests?  I doubt it.  Write mock classes for unit tests and real classes for real code, and if they happen to look the same, that's ok.</p>

Title: Moving from mock to real objects?

Body:
I'm like doing TDD so I started everything mocking objects, creating interface, stubbing, great.

The design seems to work, now I'll implement the stuff, a lot of the code used in the stubs are going to be reused in my real implementation yay!

Now should I duplicate the tests to use the real object implementation (but keeping the mocks object of the sensitive stuff like Database and "services" that are out of my context (http calls, etc...)) Or just change the mocks and stubs of the actual tests to use the real objects.......

So the question is that, keep two tests or replace the stubs, mocks?

And after that, I should keep designing with the mocks, stubs or just go with real objects?

(Just making myself clear I'll keep the mock object of the sensitive stuff like database and services that are out of my context, in both situations.)

EDIT

[Fact]
public void Change_status()
{
    var dbContext = MockRepository.GenerateStub<IDbContext>();
    var repository = MockRepository.GenerateMock<IRepository<Foo>>();

    var predicate = MockRepository.GenerateStub<Func<Foo, bool>>();
    repository.Expect(x => x.Get(predicate)).Return(_foo).Repeat.Once();
    dbContext.Expect(x => x.Commit());

    var ctl = MockRepository.GenerateStub<IFooCtl>();
    ctl.Stub(x => x.RejectRequest(_fooView)).WhenCalled(delegate
    {
        var foo = repository.Get(predicate);
        foo.Status = Status.Rejected;
        _fooView.Status = Status.Rejected.ToString();

    }).Return(true);

    ctl.RejectRequest(_fooView);

    repository.VerifyAllExpectations();
    dbContext.VerifyAllExpectations();
    Assert.True(_fooView.Status == "Rejected");
    Assert.True(result.Count() == 1);
}
```

<p>This is a test, where I mock the repository, context and stub the facade. So what I'm trying to say is if I should change the stub of the facade to use the "real" code so this should be tested as</p>

<pre class="lang-csh prettyprint-override"><code>[Fact]
public void Change_status()
{
    var dbContext = MockRepository.GenerateStub<IDbContext>();
    var repository = MockRepository.GenerateMock<IRepository<Foo>>();

    var predicate = MockRepository.GenerateStub<Func<Foo, bool>>();
    repository.Expect(x => x.Get(predicate)).Return(_foo).Repeat.Once();
    dbContext.Expect(x => x.Commit());

    var ctl = new FooCtl(loanRepository, happyLoanDbContext);
    var result = ctl.RejectRequest(_loanView);

    repository.VerifyAllExpectations();
    dbContext.VerifyAllExpectations();
    Assert.True(_result);
}
</code>```

Or if I should leave everything mocking and stubbing that tests the designs and create new ones that tests the implementation.

EDIT

Thanks for all your answer, I think I understand it better, I must know which is my SUT and test that, no mock or stub the SUT just the components that will help the SUT to pass the test


问:
Should I demand unit-testing from programmers?
I work at a place where we buy a lot of IT projects. We are currently producing a standard for systems-requirements for the requisition of future projects. In that process, we are discussing whether or not we can demand automated unit testing from our suppliers.

I firmly believe that proper automated unit-testing is the only way to document the quality and stability of the code. Everyone else seems to think that unit-testing is an optional method that concerns the supplier alone. Thus, we will make no demands of automated unit-testing, continous testing, coverage-reports, inspections of unit-tests or any of the kind. I find this policy extremely frustrating.

Am I totally out of line here?

Please provide me with arguments for any of the opinions.

答:
You are paying, you can demand whatever you want, including copies/reports of all their unit testing.

You could even write the tests, or at least the test specifications yrself.

I agree with your view in that its a very good measure of code quality. If a supplier refused this demand it would ring alarm bells, why wouldn't they want to do it - they have low quality standards and take shortcuts ?


答:
Well, for developing the business logic for my company, I can't keep the code because it's illegal & personal property of the company. As the developer, I know how to develop that logic, so I can keep that logic in my mind. Basically by default it is stored in your mind, and if you need it next time, then automatically you should implement the logic/better logic than the previous one. It's the human nature & intelligence. :)

But the issue creates when you develops some utility logic, they are re-usable & always important, you may need it frequently in different projects. So you should want to keep it with you.

I have an alternate solution to that. Just create a without source/documentation JAR for thos utilitiess and add it as an external third-party JAR in your project. Probably by doing this you can confirm your responsibility as well as your self satisfaction that you have the code ;)


答:
The cost of not having unit tests depends on how much you will be extending/supporting the code yourselves.  Getting to inspect parts of the code to get an idea of quality would also be important.

If you are just buying the projects so you can use them like a 3rd party library and don't believe you will modify them, then the risk of lower-quality code is less, so long as it actually works.

These are ultimately business decisions, although you have to make sure whoever is making the decision is aware of the technical valuation as well.  If you need to explain it to management, explain it is like buying a used car.  Ultimately it's up to the buyer to decide if it's worth it, but taking it to a mechanic is a good idea so you know you aren't getting a lemon.

Title: Should I demand unit-testing from programmers?

Body:
I work at a place where we buy a lot of IT projects. We are currently producing a standard for systems-requirements for the requisition of future projects. In that process, we are discussing whether or not we can demand automated unit testing from our suppliers.

I firmly believe that proper automated unit-testing is the only way to document the quality and stability of the code. Everyone else seems to think that unit-testing is an optional method that concerns the supplier alone. Thus, we will make no demands of automated unit-testing, continous testing, coverage-reports, inspections of unit-tests or any of the kind. I find this policy extremely frustrating.

Am I totally out of line here?

Please provide me with arguments for any of the opinions.


答:
I firmly believe, that proper automated unit-testing is the only way to document the quality and stability of the code.

The thing is that you won't (or very rarely at least) get proper automated unit-testing by forcing it on people. That's a good way to get shitty tests and drive up the cost of the projects.

Personally, I would look towards some demand or SLA that involves quality; regardless of how it is accomplished. 10 years ago unit tests were infrequent at best. You don't want to handcuff your suppliers in 10 years when we have better methods to ensure quality but your outdated policy requires them to use the old way.


问:
How to design highly scalable web services in Java?
I am creating some Web Services that would have 2000 concurrent users. The services are offered for free and are hence expected to get a large user base. In the future it may be required to scale up to 50,000 users.

There are already a few other questions that address the issue like -
https://stackoverflow.com/questions/2567254/building-highly-scalable-web-services

However my requirements differ from the question above.

For example - My application does not have a user interface, so images, CSS, javascript are not an issue. It is in Java so suggestions like using HipHop to translate PHP to native code are useless.

Hence I decided to ask my question separately.

This is my project setup -

Rest based Web services using Apache CXF

Hibernate 3.0 (With relevant optimizations like lazy loading and custom HQL for tune up)

Tomcat 6.0

MySql 5.5

What are the best practices to abide by in order to make a Java based application scalable?

答:
Good question. Probably hard to say which is best approach, but will try from my experience.

The best way to scale the Java based web application is to write it as stateless as possible (if you could). This allows you to horizontally scale the application, where you can add tomcat servers if there are more concurrent users.

However, as you noted, there could be issue with the database connections. But the question I have is, how are you getting the data? Is it user generated or you get the data from third party? This is very important because, if you are giving a service to your user with the data aggregated from third party application (say FB, Twitter etc), then what you can follow, is write to master database and replicate the data over to slave databases which are allocated to each tomcat instances. Then each tomcat server can get from its own slave database.

```<code> Are there faster alternatives to Mysql?
</code>```

You can go for MySQL cluster which have in-memory datastore. But beware of the fact that the application may need some changes. The sql joins are not well supported in MySQL cluster though in the latest version there are improvements for the same. If the cost is not a factor, then you can try Oracle.

The caching solution definitely will improve the performance. But then, it all depends on the architecture of the whole application. You should be well aware of when to push data to the cache, when to make it dirty(remove from cache).

Regarding distributing the load in multi server environment, I would suggest you to use load balancer than to use Apache for load balancing.

OwnerDisplayName: Kshitiz Sharma

Body:
Good question. Probably hard to say which is best approach, but will try from my experience.

The best way to scale the Java based web application is to write it as stateless as possible (if you could). This allows you to horizontally scale the application, where you can add tomcat servers if there are more concurrent users.

However, as you noted, there could be issue with the database connections. But the question I have is, how are you getting the data? Is it user generated or you get the data from third party? This is very important because, if you are giving a service to your user with the data aggregated from third party application (say FB, Twitter etc), then what you can follow, is write to master database and replicate the data over to slave databases which are allocated to each tomcat instances. Then each tomcat server can get from its own slave database.

 Are there faster alternatives to Mysql?

You can go for MySQL cluster which have in-memory datastore. But beware of the fact that the application may need some changes. The sql joins are not well supported in MySQL cluster though in the latest version there are improvements for the same. If the cost is not a factor, then you can try Oracle.

The caching solution definitely will improve the performance. But then, it all depends on the architecture of the whole application. You should be well aware of when to push data to the cache, when to make it dirty(remove from cache).

Regarding distributing the load in multi server environment, I would suggest you to use load balancer than to use Apache for load balancing.

OwnerDisplayName: Chandra


答:
I dealt with the issue in the past, but still feel I have lots to learn on the field. I find this to be one of the most interesting fields there are in software development nowadays, here are some thoughts about this:

MySQL is fair enough database unless you're working with massively huge amount of data, and in this case you might consider NoSQL database, but you should carefully examine what is the best NoSQL database for your needs.

You should implement caching at your system - try to cache as much read-only data as much as possible, or define some caching strategies - for example, we had a scenario in which it was valid for a user to see "old data" as long as the recent update took place in the last hour.
I would consider JBoss Cache, or maybe Infinispan (which is more like a distributed data structure)  or other popular caching framework for this.

In addition, as you mentioned tomcat, I assume you work in some request-respone module. Try to consider using a cache that exists in a scope of a given request, this can be even a simple HashMap that is associated with the thread local storage.
 My idea here quite resembles to first level cache at Hibernate.

You should remember that files, transactions and other resources are expensive in terms of keeping them open. Make sure you close files and transactions as soon as possible, or you will end up with bugs that will reproduce on large scale setups

In addition you must understand what 2000 concurrent users - does this mean that 2000 users are accessing your server at once, or are they using your system? Distinguish between cases where 2000 users try to open a socket to your server, and a case where only 500 are, and 1500 are currently looking at results, of filling input at client side.

You should consider using clustering - you will have to deal with issues like load balancing, sticky session (which means the load balancer will redirect a request to the same server for the same session) and more.

If you need to have synchronization code - choose synchronization strategy carefully. I saw some systems in which a simple lock was used, but a ReaderWriterLock could have improved things, as most access was read-only.

Consider having client side caching and validation if possible, try to save calls to server, and to send only differences of data, in case most of your response for a request with same parameter does not change.
 For example, at oVirt open source project we request to get statistics of a given virtual machine. some of the data  of the VM rarely changes, so we send only MD5 of it, if the data changes the MD5 value is changed as well , we perform a request to get the full data, and not just the MD5.

I mentioned hibernate before - I would reocmmend you to carefully consider using it - if you need to perform lots of writes, and less reads, Hibernate might not be ideal for you, and you should consider maybe working with Spring-JDBC as a wrapper over JDBC.

Index your database wisely, and use a correct db scheme. Consider using a layer of stored procedures as they are precompiled and optimized

I would like to state that at past, I dealt with a system (single node) on mysql (mostly read only access) with jboss 4.2.1 and managed to reach 2000 concurrent users
 (not accessing at once in terms of opening 2000 sockets against our server), but using/browsing our system, using JBoss Cache and preloading to the cache some of the most accessed data, or data we realized is going to be "hot and popular" but our solution was good for our architecture and our flows,
 so as I say in these cases -

There are more tips and tricks , but it really depends on your architecture, and what flows you need to have in your system. Good luck!

Title: How to design highly scalable web services in Java?

Body:
I am creating some Web Services that would have 2000 concurrent users. The services are offered for free and are hence expected to get a large user base. In the future it may be required to scale up to 50,000 users.

There are already a few other questions that address the issue like -
https://stackoverflow.com/questions/2567254/building-highly-scalable-web-services

However my requirements differ from the question above.

For example - My application does not have a user interface, so images, CSS, javascript are not an issue. It is in Java so suggestions like using HipHop to translate PHP to native code are useless.

Hence I decided to ask my question separately.

This is my project setup -

Rest based Web services using Apache CXF

Hibernate 3.0 (With relevant optimizations like lazy loading and custom HQL for tune up)

Tomcat 6.0

MySql 5.5

What are the best practices to abide by in order to make a Java based application scalable?

OwnerDisplayName: zaske


答:
I'm currently setting up a similar system (on a professional level) and this is the design I've chosen:

Two Nginx loadbalancers (both active, both failover for the other, balanced with DNS round robin)

Two MySQL Databases in master master replication mode

Two Tomcat instances as a tomcat cluster

Two Memcached instances for both caching and session state sharing for the Tomcat cluster

This will achieve a redundant, high availability, scalable solution.

The loadbalancers (on decent hardware) will easily loadbalance a saturated 1gbit line each. This is also a great place for SSL offloading.

You can save your session info in memcached. In case a tomcat instance fails, another tomcat instance can retrieve relevant session information and the clients won't notice a thing. Don't forget to combine this with sticky sessions too. (To keep network traffic down)

Tomcat clustering also has an option to share session information among the cluster in real time, without using memcached. Although I think performance wise, using Memcached will be better.

If you need more power in any of these applications:

Nginx: Add more loadbalancers, although I don't think this will be the bottleneck very soon.

Tomcat: you can easily increase the size of the Tomcat cluster or add more clusters

Mysql: Add some read-only slaves or increase the cluster size (depending on your application, but since you wrote a REST-based application, this should not be a problem)

Memcached: Add more nodes, Memcached scales pretty well I believe.

I don't know how your application is build and what the big resources hogs are, but if you see a high database load (during your loadtests!), adding a cache between the application and database could certainly improve performance a lot. But don't forget that not everything is cachable, if your queries are always different, caching won't help (much)

My advice would be to download VMware Workbench (or similair virtualization software) and try to create a simple setup. No loadbalancing or clustering, just the basics and work from there. One by one add more features (balancing, caching, clustering, etc.) and make sure to do some research on each topic, so you'll know you made the right pick.

If you keep running the same performance tests during this process, you can see for yourself if using X is better than using Y in your setup, or what impact caching will have, etc.

In the end, a setup like this really depends on the requirements of your application and its clients, everything can be done in various ways, each with it's own strengths and weaknesses.

Any more questions?

Good luck!

Wesley

OwnerDisplayName: Wesley


问:
Use my own GPL licensed code in a commercial product
I am developing a software project in Java/Swing licensed under GPL v3.
Later, I want to create a Android application which uses the algorithms of the Java/Swing application. This Android app will be a commercial product (sold on Google Play Store).

Is this a problem, when I use my OWN GPL code in a commercial SW developed by me?

答:
No, there's no problem as you own the code (and the copyright). You can do whatever you'd like with it. You could also allow other people to do the same for an additional fee if you provide  them with a copy under a different license.

In the past, I've changed my GPL code to do something that a client wanted, and then provided them a copy under a two clause BSD license (specifically so they could link to it in a proprietary application).

There is one caveat, if you accept more than trivial patches from people offered to you under the terms of the GPL 3, you'll need to get them to sign a copyright assignment (so that you retain full ownership of the copyright). If this is just a one person project, you don't have to worry about that.

OwnerDisplayName: Andreas Freitag


答:
Personally I think that in your case you should be thinking in terms of acceptance tests instead:

You have a black box given to you, and you expect it to behave in a certain way.

You will not pay until it does.

Write unit tests exercising the behavior you need to see, and if they fail, they have to fix it.

Also note that this is a matter of trust.  If you do not trust your supplier then you need to get the source code, inspect it, and compile it yourself.  Anything less than that mean that you at least trust them some.


答:
I found this article on buying custom software quite useful: http://blog.8thlight.com/paul-pagel/2012/06/20/entrepreneurs-guide-to-buying-software.html

The number one question they recommend to ask is whether the supplier writes tests.


答:
You are absolutely right that your project needs automated unit-testing, continuous testing, coverage-reports, and inspections of unit-tests.

However Demanding things will not achieve the results you desire as others have detailed.

Your challenge is to explain and persuade people - a much harder skills!

I would start initially with management, explaining the pro's and con's of testing and the payoff down the road.  Please be careful to not communicate the emotion behind statements like 'I write PROPER unit tests' (capitalization yours).  You don't want to 'shout' the words (as ALL CAPS implies) you will to persuade and convince people so that they themselves can pick the right solution.

Ultimately if you can't introduce these methodolgies and get them embraced where you are, plus if you are as passionate about them as you state (which is good!) I would on to a different company as there are many that do value these things and would welcome you on board.  Just make sure you are up front about them in interviews so they know where your passions lie and if you'll be a good fit.


答:
I doubt very much that your management will be willing to pay for proper unit testing in a contract. Proper unit test cost just as much as the code they test, but give little perceived value to the end user so they are not going to be seen as equally valuable. No quality development firm is going to be willing to spend the development effort on unit tests for a lesser cost than other parts, because they aren't hurting for work, they can make more finding 2 contracts that take the same amount of time with no unit test requirements.

Demanding unit tests will likely increase your received quotes to an unreasonable level, and is likely going to be the first concession made to get a lower price.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Get into a rut early: Do the same process the same way. Accumulate idioms. Standardize. The only difference(!) between Shakespeare and you was the size of his idiom list - not the size of his vocabulary.

--Alan J. Perlis

LastEditorDisplayName: Roger Pate


问:
Fix bugs, or wait for the customer to find them?
Do other people fix bugs when they see them, or do they wait until there's crashes/data loss/people die before fixing it?

Example 1

```<code> Customer customer = null;
 ...
 customer.Save();
</code>```

The code is clearly wrong, and there's no way around it - it's calling a method on a null reference. It happens to not crash because Save happens to not access any instance data; so it's just like calling a static function. But any small change anywhere can suddenly cause broken code that doesn't crash: to start crashing.

But, it's also not inconceivable that correcting the code:

```<code>Customer customer = null;
...
customer = new Customer();
try
   ...
   customer.Save();
   ...
finally
   customer.Free();
end;
</code>```

might introduce a crash; one not discovered through unit tests with complete coverage, and manual user testing.

Example 2

```<code>float speed = 0.5 * ((G * mass1 * mass2) / R) * Pow(time, 2);
</code>```

People knowing physics will recognize that it's supposed to be R2 in the denominator.

The code is wrong, it's absolutely wrong. And overestimating the speed will cause the retro-rockets to fire too soon, killing all the occupants of the spacecraft.

But it's also possible perhaps having it over-estimate the speed is masking another issue: the air-bags can't deploy while the shuttle is moving too fast. If we suddenly fix the code:

```<code>float speed = 0.5 * ((G * mass1 * mass2) / Pow(R, 2)) * Pow(time, 2);
</code>```

Now the speed is accurate, and suddenly airbags are deploying when they shouldn't.

Example 3

Here's an example that i had recently, checking if a string contains invalid characters:

```<code>if (StrPos(Address, "PO BOX") >= 0)
{
   //Do something
}
</code>```

What if it turns out there's a bug in the Do something branch? Fixing the obviously incorrect code:

```<code>if (StrPos("PO BOX", Address) >= 0)
{
   //Do something
}
</code>```

Fixes the code, but introduces a bug.

The way I see it there are two possibilities:

fix the code, and get blamed for breaking it

wait for the code to crash, and get blamed for having a bug

What do you politically do?

Example 4 - Today's real world bug

I am constructing an object, but calling the wrong constructor:

```<code>Customer customer = new Customer();
</code>```

Turns out that the "parameterless" constructor is actually an parameterized constructor from  further back in the inheritance chain:

```<code>public Customer(SomeObjectThatNobodyShouldBeUsingDirectly thingy = null)
public Customer(InjectedDependancy depends)
</code>```

Calling it is a mistake, since it bypasses all the subsequent constructors.

I could change the object's lineage to not expose such a dangerous constructor, but now I have to change the code to:

```<code>Customer customer = new Customer(depends);
</code>```

But I can't guarantee that this change won't break anything. Like my Example 1 above, perhaps someone, somewhere, somehow, under some esoteric conditions, depends on the constructed Customer to be invalid and full of junk.

Perhaps the Customer object, now that it is properly constructed will allow some code to run that previously never did, and now I can get a crash.

I can't bet your wife's life on it.

And I can test it from here to Tuesday, I can't swear on your daughter's life that I didn't introduce a regression.

Do I:

Fix the code and get blamed for breaking it? or

Leave the bug, and get blamed when the customer finds it?

答:
Neither. There is a third way: find a way to prove that "the problematic code" is actually causing issue from a business point of view. Confirm what you find with BA/QA or at least your manager. Then plan the fix when everyone is aware of issue.

There are more possible scenarios other than a valid bug in the cases you mentioned:

The code you are looking at are some dead code. It's possibly because like ysolik said: customers always find bugs. If they didn't, maybe the code never gets executed.

There was a WTF situation where the obvious error did have its purpose. (We are talking about production code, anything could have happened, right?)

Business/customers already knew about the issue but don't feel necessity to the fix.

Maybe more...

In any case above, if I am a manager, I don't want a developers to use his/her judgment and fix the "error" in place. Fixing the error in place may help in most of the time, but when it goes wrong, it may cause more trouble than its good intention.


答:
If you are the sole copyright holder (i.e., the owner), you can do anything you want with the code, including doing a derivative version of the code where the only change is to the license. Licenses are just descriptions of the conditions placed by the owner(s) on the non-owning users of the code. They do not constrain the owner.

When there is multiple ownership, things get more complex (formally, all copyright holders have to agree in order to change the license). There's a gray area about what sort of contribution would be required by someone for them to be a copyright holder; its almost certainly not done by mechanical count of lines modified as a substantive contribution could be very short and a non-substantive one very long (e.g., converting all the indentation to tabs or spaces). We can't assess the extent to which this applies in your situation, except to point out that someone else downloading and using the code doesn't obligate you to grant them ownership rights.

If you write all of it yourself, you don't need to pay much attention at all to the complexity in the previous paragraph. You can just go ahead and do what you want to do.

A separate point is if you are working for a company that is the owner of the code. In that case, it's the company's decision and you're just acting on the company's behalf. It's no more complex than before provided the company is the sole owner of the code.

Title: Use my own GPL licensed code in a commercial product

Body:
I am developing a software project in Java/Swing licensed under GPL v3.
Later, I want to create a Android application which uses the algorithms of the Java/Swing application. This Android app will be a commercial product (sold on Google Play Store).

Is this a problem, when I use my OWN GPL code in a commercial SW developed by me?


问:
Ways to break the "Syndrome of the perfect programmer"
I am probably not the only one that feel that way. But I have what I tend to call "The syndrome of the perfect programmer" which many might say is the same as being perfectionist but in this case it's in the domain of programming. However, the domain of programming is a bit problematic for such a syndrome.

Have you ever felt that when you are programming you're not confident or never confident enought that your code is clean and good code that follows most of the best practices ? There so many rules to follow that I feel like being overwhelmed somehow. Not that I don't like to follow the rules of course I am a programmer and I love programming, I see this as an art and I must follow the rules. But I love it too, I mean I want and I love to follow the rules in order to have a good feeling of what im doing is going the right way.. but I only wish I could have everything a bit more in "control" regarding best practices and good code.

Maybe it's a lack of organization? Maybe it's a lack of experience? Maybe a lack of practice? Maybe it's a lack of something else someone could point out? Is there any way to get rid of that syndrome somehow ?

答:
You really need to be pragmatic about programming. Yes, we all like to do things right, but you get paid for delivering working software, not for polishing it for the rest of your life.

The approach to take is to "get it done" in your professional life. Deliver and move on. Save your perfectionism for personal projects.


答:
Prioritize. First things first. Focus on what matters.

Your priorities may vary, but in general you should care about:

Correct code

Maintainable code

Clean code

Simple, elegant code

Efficient code

Maybe in that order. However, the first point is the most important. Without it, code is useless. What do you do with a program which doesn't work correctly?

Make it work, everything else is near irrelevant for solving the problems you need to solve. Of course, I too suffer from this. What I've learned that helps is to just focus on solutions which work. That is enough. That is 99 % of the job.

You might want to think about something like good code. What is it? What kind of people write it? How to write good code? It's very simple. Write code that works. Working code is good code. Everything else comes later.

Of course, when writing code in professional, team environment, obvious, readable code and maintainable code become increasingly important. However, still the first task is to make it work, and focus on that. Only then you can start refining and refactoring for better - if needed.

It is often quite obvious that code correctness is very important - yet we all fail to embrace it's importance when writing code. We cut corners, we use premature optimization, we try to write elegant code even before we have working code written. It's the human nature to strive for perfection from the very beginning, but programming and software development are iterative processes, and priorities exist. Thus, again, make it work, worry about everything else later. Understand the importance of correct code and strive for it.

While there are tons and tons of so-called good practices, I think common sense is the most important, think about why the practices are considered good, when and where to apply them. Don't strive to meet every single bit of the good practices though. There is no replacement or substitute for personal experience. You can't avoid common pitfalls - no matter how many books you read, seminars you attend or whatnot. What matters is learning by doing, doing things correctly and having fun - whenever it's possible.

Title: Ways to break the "Syndrome of the perfect programmer"

Body:
I am probably not the only one that feel that way. But I have what I tend to call "The syndrome of the perfect programmer" which many might say is the same as being perfectionist but in this case it's in the domain of programming. However, the domain of programming is a bit problematic for such a syndrome.

Have you ever felt that when you are programming you're not confident or never confident enought that your code is clean and good code that follows most of the best practices ? There so many rules to follow that I feel like being overwhelmed somehow. Not that I don't like to follow the rules of course I am a programmer and I love programming, I see this as an art and I must follow the rules. But I love it too, I mean I want and I love to follow the rules in order to have a good feeling of what im doing is going the right way.. but I only wish I could have everything a bit more in "control" regarding best practices and good code.

Maybe it's a lack of organization? Maybe it's a lack of experience? Maybe a lack of practice? Maybe it's a lack of something else someone could point out? Is there any way to get rid of that syndrome somehow ?


答:
The simplest way to avoid this problem is to only change what hurts. Do not polish code that is correct, readable and maintainable, even if you think that some changes might make it even better. But once you are e.g. trying to change something and stuble over a variable of which the purpose is unclear, or a function that is just too long to comprehend, fix it. Not sooner.

That doesn't mean that you shouldn't strive for good, clean code in the first place, of course you should, but you should consider your first attempt "good enough" unless proven otherwise.


答:
I think the best antidote to this is to remind yourself that all those best practices and code cleanliness rules don't exist for their own sake, nor does the code itself.

In the end, what matters more than anything else is that the software works and can be used. And that won't happen if you don't finish it.

I don't like the comparison of coding to art, but in this regard it works: artists (especially authors) also often want to keep working on a piece because there's always something that's not perfect. But what value is there in perfection when it delays publication indefinitely and thus prevents anyone from appreciating the work?


问:
Where does a scrum master draw the line with blocking issues?
I understand the concept that a Scrum Master should remove impediments. However I'd like to know where exactly the line should be drawn. For example a team member might have an impediment whereby they need to get support to log onto a live server and get some details. They can't progress a bit of work until this is done. Its a blocking issue essentially. But should it be the Scrum master that goes to the Ops department and does this for the developer or if the developer can do it themselves should they just do it themselves. At what point does an issue become a blocking issue?</p>

答:
It becomes a blocking issue the moment it's stopping someone from doing their job, whether that is developing, testing, designing or anything else that advances the product towards delivery. If the person it is blocking can solve it themselves (as easily as anyone else) then it's not blocking them.

If it is blocking them then the Scrum Master owns the problem. That doesn't mean the Scrum Master has to personally solve it. He just has to figure out what the simplest solution is and make sure it happens.

If that is contacting Ops direct, he should do it. If it's getting a Dev to contact them (maybe the Dev understands the technical conversation that needs to happen better than the Scrum Master), he should do that.

Whatever it takes, it just needs unblocking and if no one is responsible then it won't happen.

So the Scrum Master is always responsible. But no one can do a job with responsibility unless they have the authority to go with it. If this is a dispute where the developer is saying "No, you're the Scrum Master, you do it for me," then the Scrum Master should be able to pull rank (on blocking issues only).


答:
Forcing automated testing on someone will not achieve the results you desire as @Joachim Sauer and @Telastyn pointed out in their comments.  For a lot of people automated unit testing is a huge shift in their thinking.  Because a lot of people write code that works, but is not very testable.  I could write a ASP.NET webpage where all the logic, querying the database, business rules, objects, etc. is in the code behind.  Will the page work?  Yes.  Is it testable using automated unit testing?  Absolutely not.  If a supplier does not have automated unit testing then it will take quite an effort to learn how to write unit tests properly and as a result of learning this, re-write or re-factor their code to make it more easily testable.  Chances are they are going to pass that cost onto you.

The fact of the matter is the supplier is giving you a product, be it a .dll or a windows application, and you expect it to work 99% of the time.  Sure there are bugs here and there, but for the most part it should work.  That is a reasonable expectation, especially if the supplier wants to retain your business.  If it is a black box then it doesn't really matter how they get it to work, they could use a human wave of testers, or a room full of monkey randomly hitting keys.  As long as it works.  But they would need to provide you with some sort of other documentation on how to use it.

However, if they gave you the source code so you could modify it, then I would expect unit tests.  I would not work with a company who doesn't supply unit tests.  How else would you know a modification you make doesn't hose the whole thing?


答:
The most important thing to realize is your code is always going to change, and there is always room for improvement.  No code is ever perfect.  More often than not, a class library you work on today will be very different six months down the road.  You learn some new technique, or find a pattern that really works for you.  As long as the code is easily maintainable and readable then you should be good.  Ideally you would have unit tests to make it easier to refactor later down the road.    </p>

<p>It is easy to get caught up in making the code look perfect and follow every standard you can think of.  It happens to all of us.  Looking at code I have written a couple of weeks ago causes me to think about making changes.  Add a property here, refactor the method there.  And it seems to happen at the end of the project.  But if you get too wrapped up in that you could end up making a showstopping bug.  I've done that a couple of times early in my career.  A couple of 3 AM bug fixing sessions cured me of that problem.    </p>

Body:
The most important thing to realize is your code is always going to change, and there is always room for improvement.  No code is ever perfect.  More often than not, a class library you work on today will be very different six months down the road.  You learn some new technique, or find a pattern that really works for you.  As long as the code is easily maintainable and readable then you should be good.  Ideally you would have unit tests to make it easier to refactor later down the road.

It is easy to get caught up in making the code look perfect and follow every standard you can think of.  It happens to all of us.  Looking at code I have written a couple of weeks ago causes me to think about making changes.  Add a property here, refactor the method there.  And it seems to happen at the end of the project.  But if you get too wrapped up in that you could end up making a showstopping bug.  I've done that a couple of times early in my career.  A couple of 3 AM bug fixing sessions cured me of that problem.


问:
Options for Application Registry
I work for a small software company (about 200 people building 8-10 applications) and I was hoping to get some advice on products that might be out there to manage the information of which clients are using which versions of our products?

The most fundamental relationship would be that a "product" has "versions" and a given "version" is used by a "client." Uses would be:

Determine which clients use which products

Determine which clients are on which versions of a product

Determine which clients are exposed to which vulnerabilities because of the version they use

Determine which clients cannot move to a new version because of a vulnerability in the new version that they may hit

Determine which clients should be approached for an upgrade

Any thoughts or product reviews would be greatly appreciated!

Thanks in advance.

答:
I would just make the program "call home" every time it's started and/or everyday (in case they never shut it down). The call home would be to a server in your company.

The product version is easy to take, and the client, well, just ask them to enter those details to keep using the product.

You can make this in very few lines of code. The server would just have an app running and listening to some port, and when a client connect to this port just wait and receive the info the client will send (version number and client ID), and store it in a database or at least a log file.

Title: Options for Application Registry


答:
Do it other way around.

Instead of "what can be done better?" seek for "what pisses me off?" till nothing does.


问:
Switching from abstract class to interface
I have an abstract class which has all abstract methods except one which constructs objects of the subclasses. Now my mentor asked me to move this abstract class to an interface.

Having an interface is no problem except with the method used to construct subclass objects. Where should this method go now?

Also, I read somewhere that interfaces are more efficient than abstract classes.  Is this true?

Here's an example of my classes

```<code>abstract class Animal {
    //many abstract methods
    getAnimalobject(some parameter) {
        return //appropriate subclass
    }
}

class Dog extends Animal {}
class Elephant extends Animal {}
</code>```

答:
That construction method should go in a new Factory class.

In object-oriented computer programming, a factory is an object for creating other objects. It is an abstraction of a constructor, and can be used to implement various allocation schemes. For example, using this definition, singletons implemented by the singleton pattern are formal factories.

A factory object typically has a method for every kind of object it is capable of creating. These methods optionally accept parameters defining how the object is created, and then return the created object.

Factory objects are used in situations where getting hold of an object of a particular kind is a more complex process than simply creating a new object. The factory object might decide to create the object's class (if applicable) dynamically, return it from an object pool, do complex configuration on the object, or other things...


答:
Your design is a bit unorthodox, Animal::getAnimalobject() is inherited to Dog and Elephant unnecessarily. What you need to do is:

Move all the abstract functions in the interface,

Have your Dog and Elephant classes implement an Animal interface,

Continue creating them via a factory method, as you currently do.

...and you'll probably want to rename Animal (the class) to AnimalFactory.

Title: Switching from abstract class to interface

Body:
I have an abstract class which has all abstract methods except one which constructs objects of the subclasses. Now my mentor asked me to move this abstract class to an interface.

Having an interface is no problem except with the method used to construct subclass objects. Where should this method go now?

Also, I read somewhere that interfaces are more efficient than abstract classes.  Is this true?

Here's an example of my classes

```<code>abstract class Animal {
    //many abstract methods
    getAnimalobject(some parameter) {
        return //appropriate subclass
    }
}

class Dog extends Animal {}
class Elephant extends Animal {}
</code>```


问:
Integrating different branches from external sources into a single Mercurial repository
Edit: Making this even clearer as the bounty is about to expire: is there a way of importing history (pulling from different SCM) directly into a specific branch with Mercurial?

I'm currently working in a company using Perforce and am making way for distributed version control with Mercurial. I've had success importing Perforce history using the perfarce (quite a suitable name, I laugh every time I see/say it) however, this only works with a single branch at a time.

Here's how my P4 integration setup works:

In perforce, create a "client", which is kind of a description of what you will be constantly updating/checking-out. This can only address one branch at a time (trunk or other).

Once you do this, run hg clone p4://<server>/<client_name>

Go to .hg/hgrc and put the perforce path line: perforce = p4://<server>/<client_name>

Work normally with the code under mercurial, do hg pull perforce to sync up, hg push to export a changelist

What I'd like to be able to do is have a perforce path per branch and have everything work in the same repository. Now, pushing is not a problem, however, if I pull the history from another branch it would end up at the default branch.

I'd like to be able to do something like hg pull perforce-R5 and have it land in mercurial's R5 branch. Even if I have no merging history, it would be sweet enough to be able to preserve the branch's history.

There are also other plugins for CVCSs that let you integrate mercurial, but AFAIK the subversion one has the same problem.

I don't think there is a straight-through way of doing this, but as long as I could automate the process with some hooks and scripts in a single Mercurial machine, that would be good enough.

Edit: To make things a little clearer:

Perforce trunk is mapped to Mercurial's default branch

Perforce R1 branch should be mapped to Mercurial's release-1 branch (same for R2, R3, etc.)

When I tell Mercurial to pull from perforce (i.e. hg pull perforce, where "perforce" is the name of the path pointing to the Perforce client) it should pull the Perforce trunk into Mercurial's default.

When I tell Mercurial to pull from perforce-R1 (i.e. hg pull perforce-R1, where "perforce-R1" is the path to the R1 client) it should pull the Perforce R1 branch to Mercurial's "release-1" branch. THIS IS THE PART I'M ASKING ABOUT.

答:
I don't believe that this can be done directly.

One option would be to use the rebase tool to move the appropriate parts of the repository to the other branch after the pull using something like the following steps:

Create desired branch, e.g. hg branch release-1

Commit new branch: hg commit -m "Created branch"

Pull the remote repository to the default mercurial branch: hg pull perforce-R1

Rebase the new pull to the desired branch: hg rebase -s <first changeset of perforce-R1> -d release-1


问:
Structuring a rails application with static data
I'm working on a rails application, and so far I've focused on the api and the functionality. But now I'm more and more reaching a point where I will want to add static content, descriptions of the software and help information. Information that is generally in a CMS system.

How do I in the best way structure this so I can still work with the application. Yet maintaining the look and feel of the rails application?

Do write a CMS in my app? That seems a bit far fetched. Are there any Gems that do this?

What is the de facto standard for architecting this scenario?

答:
It depends on the scenario. So far we needed a few 3-4 pages of static pages. so we made a separate controller for such static pages. as they are not needed to be handled by rails each time, we enabled page caching for them. However, these are implemented when we need to match the layout. When we don't need to use the layout, we better put them in /public directory.

now i've seen several similar questions recommended to use high volatage. i guess you can give it a try. you can also check this discussion.

a cms may be appropriate when the static pages will be created dynamically, i mean it will be created after the application is deployed by user without the help of developers. if you already know that you have a few static pages, i guess it is better you create them during development. but when you foresee that in future they may grow, it's surely good idea to implement a basic, at least, cms.


答:
If there's clearly a crasher, or something wrong, then you should fix it. If there's an ambiguity in the spec, i.e. if you find yourself thinking "well the customer might expect this, but then it looks like it might be a bug" or a problem in the spec, like "we've been asked to do this but it sucks" then you need to find out what to do. Throwing the code over the wall and waiting for customer feedback is bad - you might ask a product manager if you have one, or ask the customer before you deploy the product.

Remember, "we know about that problem and will fix it in a future release" is synonymous with "we know about that problem but don't care about you enough to avoid you dealing with it".

Title: Fix bugs, or wait for the customer to find them?

Body:
Do other people fix bugs when they see them, or do they wait until there's crashes/data loss/people die before fixing it?

Example 1

```<code> Customer customer = null;
 ...
 customer.Save();
</code>```

The code is clearly wrong, and there's no way around it - it's calling a method on a null reference. It happens to not crash because Save happens to not access any instance data; so it's just like calling a static function. But any small change anywhere can suddenly cause broken code that doesn't crash: to start crashing.

But, it's also not inconceivable that correcting the code:

```<code>Customer customer = null;
...
customer = new Customer();
try
   ...
   customer.Save();
   ...
finally
   customer.Free();
end;
</code>```

might introduce a crash; one not discovered through unit tests with complete coverage, and manual user testing.

Example 2

```<code>float speed = 0.5 * ((G * mass1 * mass2) / R) * Pow(time, 2);
</code>```

People knowing physics will recognize that it's supposed to be R2 in the denominator.

The code is wrong, it's absolutely wrong. And overestimating the speed will cause the retro-rockets to fire too soon, killing all the occupants of the spacecraft.

But it's also possible perhaps having it over-estimate the speed is masking another issue: the air-bags can't deploy while the shuttle is moving too fast. If we suddenly fix the code:

```<code>float speed = 0.5 * ((G * mass1 * mass2) / Pow(R, 2)) * Pow(time, 2);
</code>```

Now the speed is accurate, and suddenly airbags are deploying when they shouldn't.

Example 3

Here's an example that i had recently, checking if a string contains invalid characters:

```<code>if (StrPos(Address, "PO BOX") >= 0)
{
   //Do something
}
</code>```

What if it turns out there's a bug in the Do something branch? Fixing the obviously incorrect code:

```<code>if (StrPos("PO BOX", Address) >= 0)
{
   //Do something
}
</code>```

Fixes the code, but introduces a bug.

The way I see it there are two possibilities:

fix the code, and get blamed for breaking it

wait for the code to crash, and get blamed for having a bug

What do you politically do?

Example 4 - Today's real world bug

I am constructing an object, but calling the wrong constructor:

```<code>Customer customer = new Customer();
</code>```

Turns out that the "parameterless" constructor is actually an parameterized constructor from  further back in the inheritance chain:

```<code>public Customer(SomeObjectThatNobodyShouldBeUsingDirectly thingy = null)
public Customer(InjectedDependancy depends)
</code>```

Calling it is a mistake, since it bypasses all the subsequent constructors.

I could change the object's lineage to not expose such a dangerous constructor, but now I have to change the code to:

```<code>Customer customer = new Customer(depends);
</code>```

But I can't guarantee that this change won't break anything. Like my Example 1 above, perhaps someone, somewhere, somehow, under some esoteric conditions, depends on the constructed Customer to be invalid and full of junk.

Perhaps the Customer object, now that it is properly constructed will allow some code to run that previously never did, and now I can get a crash.

I can't bet your wife's life on it.

And I can test it from here to Tuesday, I can't swear on your daughter's life that I didn't introduce a regression.

Do I:

Fix the code and get blamed for breaking it? or

Leave the bug, and get blamed when the customer finds it?


问:
Why is it good to split a program into multiple classes?
I'm still a student in high school (entering 10th grade), and I have yet to take an actual computer course in school. Everything I've done so far is through books. Those books have taught me concepts such as inheritance, but how does splitting a program into multiple classes help? The books never told me.

I'm asking this mainly because of a recent project. It's an arcade video game, sort of like a Flash game as some people have said (although I have no idea what a Flash game is). The thing is, it's only one class. It works perfectly fine (a little occasional lag however) with just one class. So, I'm just asking how splitting it into multiple classes would help it.

This project was in Java and I am the only person working on it, for the record.

答:
Object oriented programming is the single best idea I've ever seen in programming.  But it isn't the best thing in all cases, you need a bit of programming experience to see the point of it, and a lot of people are claiming to do OOP when they're not.

If you can look up "structured programming" you'll probably find something more immediately useful.  (Make sure you read about old structured programming.  Old terms often get new, fancier meanings, and you don't need anything fancy yet.)  This is a rather simple concept about breaking your program down into subroutines, which is a lot easier than breaking it down into objects.  The idea is your main program is a short routine that calls subroutines ("methods" in Java) to do the work.  Each subroutine only knows what it's told by its parameters.  (One of those parameters might be a file name, so you can cheat a bit.)  So looking at the heading of a subroutine/method gives you a quick idea of what it does, and knowing what the methods in the main program do let you see what it does almost at a glance.

Then all the subroutines are broken down similarly till a few lines of code without any method calls will do the job.  A main program that calls a few methods, each of which calls a few methods, each of which....  Down to small simple methods that do the work.  In this way, you can look at any part of a very large program (or small program) and quickly understand what it does.

Java is very specifically designed for people who are writing Object Oriented code.  But even the most intense OO program uses some structured programming, and you can always subvert any language.  (I did OO in plain C.)  So you can do SP, or anything else, in Java.  Forget classes and focus on big methods that can be broken down into small, managable ones.  I should add that SP helps a lot with letting you reuse your code, and also with the DRY (google it, but it means "Don't Repeat Yourself") principle.

Hopefully I've explained why and how to split up your code into multiple parts without bringing in "classes".  They're a great idea and are just the thing for games and Java's a great language for OOP.  But it's better to know why you're doing what you're doing.  Leave OOP alone until it starts to make some sense to you.


答:
I firmly believe, that proper automated unit-testing is the only way to document the quality and stability of the code.

It surprises me how common this thinking is. Automated, yes. Unit testing (alone), no. There's way more to automated software testing than unit tests alone. What about integration, system, functional, QA? For some reasons people tend to think, "Ok, so we have proper unit tests. Done with testing, call it friday evening!". Unit testing is just the begining.

Anyways, back on topic. I agree with others saying that forcing anything on anybody will probably yield results opposite to those desired. You never know how team works, maybe they got million dollar worth testing department and never wrote single unit test.

At my first job I used to work in a place where we had 0 unit tests (we were bunch of juniors throw at more or less serious stuff). Believe it or not, it worked. Sure, nobody was confided why this bug got fixed, or what this fix broke, but it worked. There were times when some absolutely random bug would pop out, but baseball bat and risk of having your appartment burnt down some extra hours can work wonders. Maybe your suppliers use similar techniques?


问:
Environment naming standards in software development?
My project is currently suffering from environment naming issues. Different people have different assumptions as to what environments should be named or what the names designate, and it's causing confusion when discussing them.  I've done a bit of research and I haven't found any standards out there.

The terms include "Local", "Sand", "Dev", "Test", "User", "QA", "Staging" and "Prod" (plus a few more that different people have asked about)

I'm not looking for just opinions, though if there's one out there that "everyone" has I'll take it - I'm trying to find definitions advanced by some sort of authority, even if it's unofficial.

Here's the environments we currently use:

Environment on the developer's PC

Shared Environment where developers directly upload code to self-test

Shared Environment where standards and functionality are tested by QA people

Shared Environment where completed and QA-checked code is approved by project requesters

Environment that mirrors the final environment as a final check and to prepare for deployment

Final Environment where code is in use

I know what I'd call them, but is there some sort of standard on this? Thanks in advance.

答:
There is no fixed definition. There are a few that are used by common practice (which you have listed). If you want to give each environment the name of a character in Toy Story, you can (will not recommend it, though).

What I would do is create a glossary for the company, in which we would give the names that we would want to use.


答:
I guess coming from a more structured, regulated industry the option of naming a server is a luxury I don't have. Our servers are named according to our company IT policy - so the actual hostname of the machine is not something we can control.

What we have done is gone the route of DNS names and aliases. The rule is the first letter identifies the general role of the server in the development process (the zone)

p = production

d = development

s = staging

t = testing

Then we have a max three letter name to identify the role of the machine

app = application

db = database

web = frontend/web

kas = caching

Following by a numeral if there are multiple machines in that zone. We publish this on the internal documentation server and provide it as part of any new documentation for projects and during the bootstrapping stage.

These are for those servers that are part of the development process. For support machines we have a more liberal policy; and when we have to provision a new auxilliary server we ask development teams to come up with a name that they prefer.

This has lead to some interesting ones, my two favorites ones are cerberus (internal proxy) box and hades (documentation server/intranet)

I'm sure this is not some best practice, but this is what we use and it works for us.

Title: Environment naming standards in software development?

Body:
My project is currently suffering from environment naming issues. Different people have different assumptions as to what environments should be named or what the names designate, and it's causing confusion when discussing them.  I've done a bit of research and I haven't found any standards out there.

The terms include "Local", "Sand", "Dev", "Test", "User", "QA", "Staging" and "Prod" (plus a few more that different people have asked about)

I'm not looking for just opinions, though if there's one out there that "everyone" has I'll take it - I'm trying to find definitions advanced by some sort of authority, even if it's unofficial.

Here's the environments we currently use:

Environment on the developer's PC

Shared Environment where developers directly upload code to self-test

Shared Environment where standards and functionality are tested by QA people

Shared Environment where completed and QA-checked code is approved by project requesters

Environment that mirrors the final environment as a final check and to prepare for deployment

Final Environment where code is in use

I know what I'd call them, but is there some sort of standard on this? Thanks in advance.


问:
Real world T4 usage
How many of you have ever used (or even know of)  the Visual Studio Text Templating Engine?

I mean, T4 templates have been around for quite some years now. The where initially included in Visual Studio 2005 SDK, and they where moved to Visual Studio 2008 core just before releasing it.

What I want to know is if this is really used out there. I mean, why doesn't the VS team invested in a descent minimal editor for the templates? It doesn't even have syntax couloring!
I know there are a couple of good T4 editors out there, but as they don't come built in, I tend to think that this is an unknown feature for most developers.

Have you ever used T4 templates in any of your projects? I'm really interested in answers that explain how they created their own T4 to accelerate, automate, or generate artifacts for your project.

答:
We use T4 in our project for several things:

Auto-generating POCO classes in our DAL when our Entity Framework model is modified.

Auto-generating SQL scripts for triggers when our Entity Framework model is modified.

So far they have been working great and have cut out a decent amount of dev time.

Title: Real world T4 usage


答:
There not only is not a fixed standard, but there really isn't a fixed pattern.  The dependencies between what you are building and the scale at which you can afford to replicate it are going to dictate what this has to look like from one sort of project to another.

I have worked with as few as one environment and as many as 13.

In the sequence you describe I would usually see them named them something like

local or dev if you don't use dev in the next step

dev or integration if this is the first deploy after merges

test or QA

uat or acceptance or QA if you didn't use QA in step 3

pre-prod, staging or performance if it a performance step for final sign-off

prod

My advice would be to agree on the names, purposes and criteria to enter and leave each for every product or per project then when you realize you need a 7th environment or only need 5 in one case for some other reason in the future discuss again with the team.

If you have team members that are getting hung up on the semantics of the names you can always just drop the names and refer to them as prod minus six through prod minus one with one manager that simply refused to let his QA staff test on an environment that was not named "QA"

If you are looking to name the servers themselves I usually suggest naming them by who's authority they are under. Usually this goes something like:

dev machines can be manipulated by developers

QA machines cannot be manipulated by developers but are also not monitored by production support

prod machines are prod support's business

most people end up using those sorts of names as prefixes or suffixes so that you have a chain like "devsqllweb" "qasqlweb" "prodsqlweb" or something like that.


答:
There are a lot of good answers here, and I definitely agree with them, but I feel that there's something more worth mentioning.

At the moment, as you've said, you're working solo on your project. However, in the future, there will be times when you will need to work in a team setting. During those times, you will be splitting the work (presumably the project will be fairly large). As a result there are a few (I guess really two major) different options. You can have multiple copies of one file, and work on separate "pieces" of the file and then "combine" them with copy and paste later and then modify so that your parts can work together, or you can split those "pieces" quite easily into different classes and discuss how you will be writing those classes, and use that knowledge to get going.

There will still need to be work to integrate all of the separate pieces together, but it will be a lot easier to maintain. Because x file contains y code and that's the code you know you need to modify. This goes into the organization thing that most of the other answers talk about.

Holding a program in one's head. Link from Giorgio

Title: Why is it good to split a program into multiple classes?

Body:
I'm still a student in high school (entering 10th grade), and I have yet to take an actual computer course in school. Everything I've done so far is through books. Those books have taught me concepts such as inheritance, but how does splitting a program into multiple classes help? The books never told me.

I'm asking this mainly because of a recent project. It's an arcade video game, sort of like a Flash game as some people have said (although I have no idea what a Flash game is). The thing is, it's only one class. It works perfectly fine (a little occasional lag however) with just one class. So, I'm just asking how splitting it into multiple classes would help it.

This project was in Java and I am the only person working on it, for the record.


答:
Agreeing with others that demandind unit tests would lead to testing for the sake of testing; something that is very counter to what you want.

In the process of vetting your suppliers; ask them what is their development process as testing is just one part of that process.

Do they have an automated build process? Do they following some management paradigm? Do they have properly trained testers and an independent quality assurance team? How about documentation standards?

These will help you judge the overall quality of their process, and in turn the quality of what they produce.


问:
How should I structure a solution for a long term project?
I'm about to create a do-everything dashboard for my team and am still having second thoughts about my project/solution structure.  Since this could be a long ongoing project, I want to get the structure right from the beginning.

This is what I had in mind:

Create a  solution named "doEverythingDashboard"

Delete the project named "doEverythingDashboard" under the solution "doEverythingDashboard"

Create winform project named "interface"

Create console applications projects for each functionality of "doEverythingDashboard"

Reference each console application in "interface"

Does this make any sense?  Would it make more sense to just have one project and create a class per functionality instead of an entire project?

答:
Since this could be a long ongoing project, I want to get the structure right from the beginning

It's pretty tricky to know up front what the correct structure for a collection of code should be, especially where the project is essentially an R&D effort (for which read: you haven't personally built such a system before1).

So don't bother; instead, FIRST write some code, THEN look at it and consider how it might be more nicely structured. Modern refactoring tools mean you don't have to get it right first time - and who's to say there's one 'right' for all time, anyway?!

And as to your last point - create new projects (ie assemblies) exactly when you want to create new units of deployment, and for no other reason. Namespaces can provide the implementation of purely conceptual divisions perfectly well.

1 this usage is from Code Complete or PragProg or something


答:
Depending on your application type, you may get some hints on project structure from open source project samples. Let me mention as well an important point, as your project moves forward you may see need to slightly change the structure or add additional layers depending on requirements and design.

There are couple places where you may look at some samples:

Codeplex

MSDN- code gallery

Open source ASP.NET projects

Dot.Net spider

Open Source Software in C#

Top 10 Open Source Projects for .NET Developers

Title: How should I structure a solution for a long term project?

Body:
I'm about to create a do-everything dashboard for my team and am still having second thoughts about my project/solution structure.  Since this could be a long ongoing project, I want to get the structure right from the beginning.

This is what I had in mind:

Create a  solution named "doEverythingDashboard"

Delete the project named "doEverythingDashboard" under the solution "doEverythingDashboard"

Create winform project named "interface"

Create console applications projects for each functionality of "doEverythingDashboard"

Reference each console application in "interface"

Does this make any sense?  Would it make more sense to just have one project and create a class per functionality instead of an entire project?


答:
How do you know the vendors are not writing unit tests.

Maybe management and the vendor had a meeting and the vendor said, the code costs $X and the unit tests costs $Y.  Penny pinching management said we just want the code.

The vendor decided to write unit tests anyway (because of quality) and just not share them with you (because of competitive advantage).

Now you need to make some major adjustments to the software.  Since you own the code, you could do it yourself or hire it out competitively (not necessarily to the original vendor).  But since you did not buy the unit tests, the original vendor will be able to do comparable quality work at a cheaper price to any competitor.