答:
It is not feasible, speaking with the current theoretical knowledge in computer science.

The easiest way to see it is this, put into your code a conjecture that hasn't been proved. (there are many of them).
You don't know if the code can get into this or that branch, you also don't know which value would let it into the branch.

So you can't really generate test cases that would go into certain branch even if you have access to the source code.

And if you think it is just software, you will get it if you try hard enough, remember after a few number increase in the encoding length of the conjecture, the search space grows exponentially. Then you have to find another way.

Title: Is it feasible and useful to auto-generate some code of unit tests?

Body:
Earlier today I have come up with an idea, based upon a particular real use case, which I would want to have checked for feasability and usefulness. This question will feature a fair chunk of Java code, but can be applied to all languages running inside a VM, and maybe even outside. While there is real code, it uses nothing language-specific, so please read it mostly as pseudo code.

The idea

Make unit testing less cumbersome by adding in some ways to autogenerate code based on human interaction with the codebase. I understand this goes against the principle of TDD, but I don't think anyone ever proved that doing TDD is better over first creating code and then immediatly therafter the tests. This may even be adapted to be fit into TDD, but that is not my current goal.

To show how it is intended to be used, I'll copy one of my classes here, for which I need to make unit tests.

```<code>public class PutMonsterOnFieldAction implements PlayerAction {
    private final int handCardIndex;
    private final int fieldMonsterIndex;

    public PutMonsterOnFieldAction(final int handCardIndex, final int fieldMonsterIndex) {
        this.handCardIndex = Arguments.requirePositiveOrZero(handCardIndex, "handCardIndex");
        this.fieldMonsterIndex = Arguments.requirePositiveOrZero(fieldMonsterIndex, "fieldCardIndex");
    }

    @Override
    public boolean isActionAllowed(final Player player) {
        Objects.requireNonNull(player, "player");
        Hand hand = player.getHand();
        Field field = player.getField();
        if (handCardIndex >= hand.getCapacity()) {
            return false;
        }
        if (fieldMonsterIndex >= field.getMonsterCapacity()) {
            return false;
        }
        if (field.hasMonster(fieldMonsterIndex)) {
            return false;
        }
        if (!(hand.get(handCardIndex) instanceof MonsterCard)) {
            return false;
        }
        return true;
    }

    @Override
    public void performAction(final Player player) {
        Objects.requireNonNull(player);
        if (!isActionAllowed(player)) {
            throw new PlayerActionNotAllowedException();
        }
        Hand hand = player.getHand();
        Field field = player.getField();
        field.setMonster(fieldMonsterIndex, (MonsterCard)hand.play(handCardIndex));
    }
}
</code>```

We can observe the need for the following tests:

Constructor test with valid input

Constructor test with invalid inputs

isActionAllowed test with valid input

isActionAllowed test with invalid inputs

performAction test with valid input

performAction test with invalid inputs

My idea mainly focuses on the isActionAllowed test with invalid inputs. Writing these tests is not fun, you need to ensure a number of conditions and you check whether it really returns false, this can be extended to performAction, where an exception needs to be thrown in that case.

The goal of my idea is to generate those tests, by indicating (through GUI of IDE hopefully) that you want to generate tests based on a specific branch.

The implementation by example

User clicks on "Generate code for branch if (handCardIndex >= hand.getCapacity())".

Now the tool needs to find a case where that holds.

(I haven't added the relevant code as that may clutter the post ultimately)

To invalidate the branch, the tool needs to find a handCardIndex and hand.getCapacity() such that the condition >= holds.

It needs to construct a Player with a Hand that has a capacity of at least 1.

It notices that the capacity private int of Hand needs to be at least 1.

It searches for ways to set it to 1. Fortunately it finds a constructor that takes the capacity as an argument. It uses 1 for this.

Some more work needs to be done to succesfully construct a Player instance, involving the creation of objects that have constraints that can be seen by inspecting the source code.

It has found the hand with the least capacity possible and is able to construct it.

Now to invalidate the test it will need to set handCardIndex = 1.

It constructs the test and asserts it to be false (the returned value of the branch)

What does the tool need to work?

In order to function properly, it will need the ability to scan through all source code (including JDK code) to figure out all constraints. Optionally this could be done through the javadoc, but that is not always used to indicate all constraints. It could also do some trial and error, but it pretty much stops if you cannot attach source code to compiled classes.

Then it needs some basic knowledge of what the primitive types are, including arrays. And it needs to be able to construct some form of "modification trees". The tool knows that it needs to change a certain variable to a different value in order to get the correct testcase. Hence it will need to list all possible ways to change it, without using reflection obviously.

What this tool will not replace is the need to create tailored unit tests that tests all kinds of conditions when a certain method actually works. It is purely to be used to test methods when they invalidate constraints.

My questions:

Is creating such a tool feasible? Would it ever work, or are there some obvious problems?

Would such a tool be useful? Is it even useful to automatically generate these testcases at all? Could it be extended to do even more useful things?

Does, by chance, such a project already exist and would I be reinventing the wheel?

If not proven useful, but still possible to make such thing, I will still consider it for fun. If it's considered useful, then I might make an open source project for it depending on the time.

For people searching more background information about the used Player and Hand classes in my example, please refer to this repository. At the time of writing the PutMonsterOnFieldAction has not been uploaded to the repo yet, but this will be done once I'm done with the unit tests.


问:
Is it feasible and useful to auto-generate some code of unit tests?
Earlier today I have come up with an idea, based upon a particular real use case, which I would want to have checked for feasability and usefulness. This question will feature a fair chunk of Java code, but can be applied to all languages running inside a VM, and maybe even outside. While there is real code, it uses nothing language-specific, so please read it mostly as pseudo code.

The idea

Make unit testing less cumbersome by adding in some ways to autogenerate code based on human interaction with the codebase. I understand this goes against the principle of TDD, but I don't think anyone ever proved that doing TDD is better over first creating code and then immediatly therafter the tests. This may even be adapted to be fit into TDD, but that is not my current goal.

To show how it is intended to be used, I'll copy one of my classes here, for which I need to make unit tests.

```<code>public class PutMonsterOnFieldAction implements PlayerAction {
    private final int handCardIndex;
    private final int fieldMonsterIndex;

    public PutMonsterOnFieldAction(final int handCardIndex, final int fieldMonsterIndex) {
        this.handCardIndex = Arguments.requirePositiveOrZero(handCardIndex, "handCardIndex");
        this.fieldMonsterIndex = Arguments.requirePositiveOrZero(fieldMonsterIndex, "fieldCardIndex");
    }

    @Override
    public boolean isActionAllowed(final Player player) {
        Objects.requireNonNull(player, "player");
        Hand hand = player.getHand();
        Field field = player.getField();
        if (handCardIndex >= hand.getCapacity()) {
            return false;
        }
        if (fieldMonsterIndex >= field.getMonsterCapacity()) {
            return false;
        }
        if (field.hasMonster(fieldMonsterIndex)) {
            return false;
        }
        if (!(hand.get(handCardIndex) instanceof MonsterCard)) {
            return false;
        }
        return true;
    }

    @Override
    public void performAction(final Player player) {
        Objects.requireNonNull(player);
        if (!isActionAllowed(player)) {
            throw new PlayerActionNotAllowedException();
        }
        Hand hand = player.getHand();
        Field field = player.getField();
        field.setMonster(fieldMonsterIndex, (MonsterCard)hand.play(handCardIndex));
    }
}
</code>```

We can observe the need for the following tests:

Constructor test with valid input

Constructor test with invalid inputs

isActionAllowed test with valid input

isActionAllowed test with invalid inputs

performAction test with valid input

performAction test with invalid inputs

My idea mainly focuses on the isActionAllowed test with invalid inputs. Writing these tests is not fun, you need to ensure a number of conditions and you check whether it really returns false, this can be extended to performAction, where an exception needs to be thrown in that case.

The goal of my idea is to generate those tests, by indicating (through GUI of IDE hopefully) that you want to generate tests based on a specific branch.

The implementation by example

User clicks on "Generate code for branch if (handCardIndex >= hand.getCapacity())".

Now the tool needs to find a case where that holds.

(I haven't added the relevant code as that may clutter the post ultimately)

To invalidate the branch, the tool needs to find a handCardIndex and hand.getCapacity() such that the condition >= holds.

It needs to construct a Player with a Hand that has a capacity of at least 1.

It notices that the capacity private int of Hand needs to be at least 1.

It searches for ways to set it to 1. Fortunately it finds a constructor that takes the capacity as an argument. It uses 1 for this.

Some more work needs to be done to succesfully construct a Player instance, involving the creation of objects that have constraints that can be seen by inspecting the source code.

It has found the hand with the least capacity possible and is able to construct it.

Now to invalidate the test it will need to set handCardIndex = 1.

It constructs the test and asserts it to be false (the returned value of the branch)

What does the tool need to work?

In order to function properly, it will need the ability to scan through all source code (including JDK code) to figure out all constraints. Optionally this could be done through the javadoc, but that is not always used to indicate all constraints. It could also do some trial and error, but it pretty much stops if you cannot attach source code to compiled classes.

Then it needs some basic knowledge of what the primitive types are, including arrays. And it needs to be able to construct some form of "modification trees". The tool knows that it needs to change a certain variable to a different value in order to get the correct testcase. Hence it will need to list all possible ways to change it, without using reflection obviously.

What this tool will not replace is the need to create tailored unit tests that tests all kinds of conditions when a certain method actually works. It is purely to be used to test methods when they invalidate constraints.

My questions:

Is creating such a tool feasible? Would it ever work, or are there some obvious problems?

Would such a tool be useful? Is it even useful to automatically generate these testcases at all? Could it be extended to do even more useful things?

Does, by chance, such a project already exist and would I be reinventing the wheel?

If not proven useful, but still possible to make such thing, I will still consider it for fun. If it's considered useful, then I might make an open source project for it depending on the time.

For people searching more background information about the used Player and Hand classes in my example, please refer to this repository. At the time of writing the PutMonsterOnFieldAction has not been uploaded to the repo yet, but this will be done once I'm done with the unit tests.

答:
TLDR: It's a bad idea (see below to read why).

First, I wanted to address this:

I understand this goes against the principle of TDD, but I don't think anyone ever proved that doing TDD is better over first creating code and then immediatly therafter the tests. This may even be adapted to be fit into TDD, but that is not my current goal.

TDD is better over writing the code first (yes, it has been proven).

Here are some of the benefits (you can also read about these in lots of online articles and books):

TDD ensures you don't write stuff you don't need (e.g. "write minimal code for the test to pass")

TDD ensures the interface of your API is optimized from the client's point of view, instead of from the implementor's point of view. The first, ensures the code will be easier to use, for client code. The second tends to polute the public API of your module with implementation details (even when you are careful to prevent this).

TDD ensures that you write code to your specs, not to an abstract idea of your algorithm

with writing code first, you find many situations where you believe the code will work, and "see no reason to write an extra test just for a hard to reach corner case" (also known as "developer lazyness", "very bad mistranslation of YAGNI", and "programmer excuse number 8"). With TDD you don't have the excuse. It may not sound like much, until you work in a team and your coleagues bull***t you with an excuse - or call you out for bull****ting them.

TDD minimizes effort (usually, when writing code first, the development loop is "implement, write tests, modify/fix implementation for tests to pass"; with TDD, it is "write tests, implement until tests pass" - which can be much shorter).

Is creating such a tool feasible? Would it ever work, or are there some obvious problems?

Given enough resources, it is theoretically possible to create such a tool.

In practice, it is doubtful you can make something like that, that trully fits generic implementations. It is easy enough to make something for a simple case, but consider that you may test an API that calls 25 other APIs internally (with each one adding to the cyclomatic complexity of your algorithm). The tool would have to do much more than the best static analizers on the market today.

The obvious problem is, the tests would not cover your (client's) requirements, in any meaningful way - they would instead cover all cases of the implementation.

A correct unit test should test that a unit of your code does what it is supposed to do, in a situation. A test generated like you mention, would test that the code does what it is implemented to do (and maybe that your code is reachable). This in no way relates to your specs.

Would such a tool be useful?

Partially (with limited functionality). It could shorten the time needed to write unit tests for a corner cases.

Is it even useful to automatically generate these testcases at all? Could it be extended to do even more useful things?

Not really. I think it would be usefull to automatically generate one testcase at a time, with the user choosing which cases he wants generated (but generating all cases would be a very low signal/noise ratio - you would have to discard most generated code as irrelevant).

ContentLicense: CC BY-SA 3.0


问:
Why And is needed when there is AndAlso
I have referred What is the difference between And and AndAlso in VB.net? to understand the difference between And and AndAlso.

I am from C# background - and C# has AndAlso only - no And.. And I don't see any practical use/advnatage of And.

Is there any practical use of And in VB.Net?

Reference

Or versus OrElse

What is the difference between And and AndAlso in VB.net?

答:
C# doesn't have "And" and "Or".  It has "&&" and "||".

"AndAlso" and "OrElse" were added to Visual Basic to provide a [new] syntax for "short-circuiting" the evaluation of conditions (which C# has always done, but Basic didn't).  There was a lot of "discussion" early on about whether the existing operators should be reworked to support this but, for compatibility with existing code, new operators were added instead.

Title: Why And is needed when there is AndAlso


答:
There might be some reasons to evaluate both statements when dealing with sideeffects: if you want both to happen!

The best example I can come up right now is logging: you have two checks (both have to be true) and want to log both checks and their results (as a sideffect in the check) - in this case VB's AND is a good idea.

Title: Why And is needed when there is AndAlso

Body:
I have referred What is the difference between And and AndAlso in VB.net? to understand the difference between And and AndAlso.

I am from C# background - and C# has AndAlso only - no And.. And I don't see any practical use/advnatage of And.

Is there any practical use of And in VB.Net?

Reference

Or versus OrElse

What is the difference between And and AndAlso in VB.net?


问:
Estimated work remaining doesn't get lower
I'm working as a developer / architect on a software project. The project manager decided not to follow the Agile principles, but to rather have an Excel sheet with all the feature requests and their estimated (remaining) effort. I'm required to update the estimated remaining time of each feature that I'm implementing weekly.

The problem is: with bugs and requirement changes constantly incoming, the remaining effort doesn't change as fast as the manager expects. Say, it was "12 days remaining" about 2 months ago, and today it's still "7 days remaining". The manager is rightfully getting nervous about this, because he can't give a release date for the potential customers and the marketing department this way. What is the best way to solve this problem? I think the main goal would be to be able to give a release date that makes sense. How could one achieve this?

Now, my suggestion at the beginning was to:

Set priorities for all the features. This didn't work out well, since about 70% of the features got priority 1, all the others got priority 2. And the verdict was: all features must be included in the first release.

Reduce the number of features, or reduce the complexity of the features which are the most difficult to implement or unnecessarily complex (meaning: no user will ever understand how it works). This also didn't bring much, all features must be implemented as they are, and even more features were added.

Add bug fixing & feature change  estimations as they come. This is what we normally do in another project at this company. The result is, that sometimes the work remaining goes up between weeks instead of going down. This also wouldn't solve the main problem (release date?).

I'm running out of ideas... The manager has told me that he thought my estimations mean the time required to write bug-free code... No comments on that remark. He also said he expected me to include the estimation of bug fixing in the initial estimation. Yes, to include the effort to solve a bug which we don't even know if it exists...

His other suggestion was that I write my tests so that they cover every possible case. It would make sense, but having such complex features and a very large and complex background service we are calling from this application, it would take forever to cover every scenario with integration tests. I don't think we can ever achieve 100% coverage.

Edit:
The questions How to answer "When will it be done?" and What can I do to get better at estimating how long projects are going to take? might appear similar, but are not relevant to my situation. I have already given an effort estimation. My question is related to the progress of the development, and changing estimations / deadline.

答:
It's a software project, therefore it's overrunning.

That's a slightly flippant answer, but this is a very common problem. You say there are "requirement changes constantly incoming": that's why you're overrunning. You absolutely have to have a requirements freeze or you will never ship. Only with the requirements frozen can you issue a release date.

Your manager also needs to be aware of the cost/quality/features tradeoff triangle. You can only have a perfect product with lots of features if you're prepared to spend decades building it. Startups and small companies tend to aim at a "minimum viable product", minimising all three quantities.

Put the spreadsheet in the revision control system. It doesn't matter if it's binary and undiffable, the important thing is to track changes. Then you can dig out the spreadsheet from three weeks ago and point out that you've done three weeks work and reduced its expected time by three weeks - but today's spreadsheet has another four weeks of features added!

Bugfixing itself usually shows up deficiencies in the specification. You have to triage bugs and focus on minimising risk to the user. It's useful if your software can fail gracefully and retry, but this option is not available for security bugs.


答:
I'm a bit worried that it's the program manager, not marketing, who is continually adding new features.  But in a sense, that's not your problem.

Whenever the manager comes up with a new feature request, try to estimate not just how long it will take to code up, but add in a generous margin for bug fixing and reversion testing caused by the change.  Anecdote: a few years ago, I was regularly asked by my then program manager to estimate the time it would take to add features.  Some time later, he told me that he always doubled every estimate I gave him.  I was only looking at how long it would take to design and code up, not how long it would take to integrate, test and debug.

If you're not already doing so, create a database of all known bugs.  For every bug, keep track of how long it took to fix.  Monitor how the number of bugs decreases over time.  From these two bits of information, you should be able to work out how long it will be before the number of outstanding bugs is trivially low.

If the number of bugs isn't noticably decreasing over time, then it's so bug-ridden that it's nowhere near ready to ship.

Title: Estimated work remaining doesn't get lower

Body:
I'm working as a developer / architect on a software project. The project manager decided not to follow the Agile principles, but to rather have an Excel sheet with all the feature requests and their estimated (remaining) effort. I'm required to update the estimated remaining time of each feature that I'm implementing weekly.

The problem is: with bugs and requirement changes constantly incoming, the remaining effort doesn't change as fast as the manager expects. Say, it was "12 days remaining" about 2 months ago, and today it's still "7 days remaining". The manager is rightfully getting nervous about this, because he can't give a release date for the potential customers and the marketing department this way. What is the best way to solve this problem? I think the main goal would be to be able to give a release date that makes sense. How could one achieve this?

Now, my suggestion at the beginning was to:

Set priorities for all the features. This didn't work out well, since about 70% of the features got priority 1, all the others got priority 2. And the verdict was: all features must be included in the first release.

Reduce the number of features, or reduce the complexity of the features which are the most difficult to implement or unnecessarily complex (meaning: no user will ever understand how it works). This also didn't bring much, all features must be implemented as they are, and even more features were added.

Add bug fixing & feature change  estimations as they come. This is what we normally do in another project at this company. The result is, that sometimes the work remaining goes up between weeks instead of going down. This also wouldn't solve the main problem (release date?).

I'm running out of ideas... The manager has told me that he thought my estimations mean the time required to write bug-free code... No comments on that remark. He also said he expected me to include the estimation of bug fixing in the initial estimation. Yes, to include the effort to solve a bug which we don't even know if it exists...

His other suggestion was that I write my tests so that they cover every possible case. It would make sense, but having such complex features and a very large and complex background service we are calling from this application, it would take forever to cover every scenario with integration tests. I don't think we can ever achieve 100% coverage.

Edit:
The questions How to answer "When will it be done?" and What can I do to get better at estimating how long projects are going to take? might appear similar, but are not relevant to my situation. I have already given an effort estimation. My question is related to the progress of the development, and changing estimations / deadline.


答:
What you experience is called

feature creep

The Dilbert site has a nice collection about this topic.

Now, my suggestion at the beginning was to: 1: Set priorities for all the features.

I would have proposed the same.

This didn't work out well, since about 70% of the features got
  priority 1, all the others got priority 2.
  And the verdict was: all features must be included in the first release.

Your Product owner or the equivalent of it is either a weak person or has a conflict of interest with the customer. Unless the resources available on your side is adequately sized, this is not going to happen from the start. Especially knowing, that in typical projects there will (and should) be feedback, and as a result there will be changes That's a given.

What turns it into a problem is the fact, that nobody in your team seems to have the balls (or maybe the authority) to tell them, that this ain't gonna work out.

Present data. Collect data about features and estimations at various stages of the project. Draw a burndown chart of it. Try to make some forecasts. You may also try to use Evidence Based Scheduling.

Smaller releases Propose to release the product in multiple smaller milestones instead of one big release. Try to get consensus about what should be part of each release. To achieve this, people will have to prioritize their wishes. Explain them, that this is a good thing for both sides.

Get backing. If the PO or the equivalent of it is the problem, try to find someone else in your company, with the necessary authority, to give you some backing. Explain the problem as above and sketch out your ideas. Make it clear, that you want the project to become a success, but are worried about the way it goes. Then ask for advice.

The key is to get them to realize, that the day has only 24 hours and resources are limited, while features wishes aren't. If they want more features, fine, but they will have to pay for it. Mainly money, but to some extent also time.

At the end, it is a team effort, and the goal is the project success. The goal is not to sink thousands of dollars only to finally fix the blame. That does not help anyone.


问:
is there any language that supports automatic evaluation of input expressions?
I'm wondering if anyone knows of a language that supports automatic-evaluation.
(not sure this is the right term. so let me describe what I mean below)

For example, a program asks for an int as its input, one can give it 2 + 2, which evaluates to an int with value 4.

Of course, one can certainly make a program that accepts this using any language, but I'm wondering if there is any language that natively supports this.

What are the plus and down sides of this?

P.S: My "ultimate" goal is to decide whether to do this in a language that I'm designing. So I'd appreciate any input especially with regard to design.

答:
If the question is "any language", the answer is yes. However, I think what you're actually asking is if there's any popular, modern, language, in which case the answer is "maybe".

One language that definitely evaluates expressions when read from the user is Sinclair Basic (at least in its ZX-81 variant), where a numeric input (like, say, 100 INPUT X) would take something like "2+2" and stuff 4 into the variable X. It also allows you to refer to variables, so you can say "10+A" and it would fetch the value of A and add 10 to it.

When it comes to modern languages, I don't know of any that will do it without at least wrapping the moral equivalent of eval around the resulting input, but in some cases you can do read-time computations via other routes.


答:
I think most of the people in software development will sooner or later go through a project like the one you describe. The good thing I can tell you: You'll learn a lot. Once you went down the hard road, you'll see things differently and your next project will already be better.

Here are some thoughts what you can do now:

It seems like your project manager has a business background and no experience with software projects. (These people use to think that programming is the same kind of work like e.g. loading parcels to a truck.) Sit down with him and explain that there's no such thing as "bug-free code" or "100% test coverage". Also explain that estimation in software development is not easy, because unlike the truck worker, you often have to estimate something which you have never done before.

You have to stop feature creep or you'll never be ready. Explain that each new feature will also slow down development of the other features, since you have complex dependencies (I guess that's the case for your system)

Your project manager has to clarify what's more important: the release date or a complete feature set? I experienced both situations, depending on the industry. But you have to make clear that this decision has to be made.

If people are not willing to give priorities, do them on your own. Of course it would be much better if priorities would come from the "product owners", but in my experience it is better do prioritize on your own than having no priorities at all (70% priority 1 is pretty much the same as "no priorities at all")

You have to include a buffer in your estimations for bug fixing etc. Sure you don't know which bugs will happen, but you do know that some bugs will happen for sure. For your estimation Excel sheet, make sure you include everything which consumes time, lets say: feature development (this is what you already have), meetings, bug fixing, testing, release / deployment work, system administration (if you have to), holidays, sickness leave, phone conferences, plus: a buffer for estimation errors

Grab a book about software project management (e.g., something about Agile, or "Ship It" from the Pragmatic Programmers is good for the beginning). This is more for the long run


答:
JavaScript is the easy answer

eval('2+2')=4

Now the problem with any language that will do this is how much control do you give the user.  What methods can and can't be called.  In JavaScript when you run Eval you can do anything the Lagrange can.  (not like there is any JS security on the web, but in other builds of JS there could be)

Title: is there any language that supports automatic evaluation of input expressions?

Body:
I'm wondering if anyone knows of a language that supports automatic-evaluation.
(not sure this is the right term. so let me describe what I mean below)

For example, a program asks for an int as its input, one can give it 2 + 2, which evaluates to an int with value 4.

Of course, one can certainly make a program that accepts this using any language, but I'm wondering if there is any language that natively supports this.

What are the plus and down sides of this?

P.S: My "ultimate" goal is to decide whether to do this in a language that I'm designing. So I'd appreciate any input especially with regard to design.


问:
Scriptable user-interfaces/frameworks for automated UI testing
I'm planning on using scripting for automated UI testing. Main application is written in c#, and I want it to be scriptable, so I can do everything end-user can do, but programmatically.

I'll avoid opinion-based questions like "What do you think of software that provides an interface for scripting, like VBA macros in Excel?", or "Can this be future of all programming, big and small?" although some inside would be great.

Here goes the question:

Which is most suitable to the purpose of building such an interface for your own application, dll-based approach or by parsing own scripting language?

答: I don't think there's any good reason to invent your own scripting language. There are several languages that are designed specifically to be embedded in other applications (eg: tcl, lua). Save yourself the trouble of inventing yet another language and instead consider adapting one of those.</p>


答:
I had one manager who I liked that described a project as "pushing a wall forward". That is, for most of the project there's an almost overwhelming span of tasks that you have to push forward at more or less the same rate -- like pushing a wall.

But at some point, he would say, you hit a critical threshold, and then the wall just sort of disappears, and you're done.

I've also heard it in the sense of "converging" and "diverging". Diverging means the scope of the project is expanding, and converging means the scope is winding down and narrowing. That's a natural process for projects -- you might be able to find some literature describing it online.

One thing to watch out for is that converging and diverging are also personal conversation style -- some people in conversation like to think more and more broadly, loop in more and more related ideas, and hate settling on answers. Convergers are the opposite -- they like to tie together ideas, summarize, and come up with clear answers. Convergers and divergers, as you might expect, can drive each other crazy.

So you might watch out that you have a diverger somewhere in the project definition, who is dissatisfied with having an answer. Apart from that, it may be that you're still in the natural process of discovering necessary work -- before you hit the crossover point where it all starts to wrap up.


问:
Is it considered Pythonic to have multiple classes defined in the same file?
In working with python for the first time, I've found that I end up writing multiple classes in the same file, which is opposed to other languages like Java, which uses one file per class.

Usually, these classes are made up of 1 abstract base class, with 1-2 concrete implementations who's use varies slightly. I've posted one such file below:

```<code>class Logger(object):

    def __init__(self, path, fileName):
        self.logFile = open(path + '/' + filename, 'w+')
        self.logFile.seek(0, 2)

    def log(self, stringtoLog):
        self.logFile.write(stringToLog)

    def __del__(self):
        self.logFile.close()

class TestLogger(Logger):

    def __init__(self, serialNumber):
        Logger.__init__('/tests/ModuleName', serialNumber):

    def readStatusLine(self):
        self.logFile.seek(0,0)
        statusLine = self.logFile.readLine()
        self.logFile.seek(0,2)
        return StatusLine

    def modifyStatusLine(self, newStatusLine):
        self.logFile.seek(0,0)
        self.logFile.write(newStatusLine)
        self.logFile.seek(0,2)

class GenericLogger(Logger):

    def __init__(self, fileName):
        Logger.__init__('/tests/GPIO', fileName):

    def logGPIOError(self, errorCode):
        self.logFile.write(str(errorCode))
</code>```

As seen above, I have a Logger base class, with a couple of implementation differences below that.

The Question:
Is this standard for python, or for any language? What problems could arise from using this implementation if any?

Please note: I'm not really looking for guidance on this specific file, but in a more general sense. What if the classes ended up being 3-5 moderately complex methods? Would it make sense to split them then? Where is the cutoff for saying you should split a file up?

答:
In short - hell yes.

Moreover, having multiple classes in a single file is sometimes very handy. Some packages (six, bottle) explicitly ship in a single file in order to easily be integrated into any third-party module without being pip installed (sometimes desirable). But, do make sure to organise your code well. Intensively use code comments and separation blocks in order to make it more readable.

ContentLicense: CC BY-SA 4.0


答: You need to freeze on a set of requirements that you are going to work on and give the ETA for it and count the time for bugs and some additional buffer time while giving the ETA. Any changes that come happen after the release of the set of requirements that you froze upon or they should go to the manager who would then request you to prioritize and give a new ETA.</p>


答:
Python2 does it automatically:

```<code>>>> x = input()
2 + 2
>>> print x
4
</code>```

It was removed in Python3, because it's a misfeature. Evaluating user input without the programmer specifically requesting it is a serious security breach, because the programmer might use it to automatically convert numeric input to numbers, but it lets the user run any Python command, and many python programmers won't even notice this when they use input(), because they test it with either numbers(which get converted correctly) or random strings(which crash like they should) and not with actual Python commands.

Body:
Python2 does it automatically:

>>> x = input()
2 + 2
>>> print x
4

It was removed in Python3, because it's a misfeature. Evaluating user input without the programmer specifically requesting it is a serious security breach, because the programmer might use it to automatically convert numeric input to numbers, but it lets the user run any Python command, and many python programmers won't even notice this when they use input(), because they test it with either numbers(which get converted correctly) or random strings(which crash like they should) and not with actual Python commands.


答:
In some ways this is your failing for not correctly "managing the client". You say they have expectations that you find unreasonable, and that's the core of the problem.

Most companies and people have no problem spending money if they think they are getting value from it. In most cases this is limited by budget, but a company will spend $2,000 if they think there is value and bawk over $2 when they think there isn't. This is fair, and it's how it should work.

Now to correct your problem, your need to do a few things.

First blow your own horn a bit. List out all the feature creep you have done and and show it off. Let the customer know that the time and money they spent has value.  If they can see the value they will be happier with the time frames.

Second, finish your tasks on time. Your failing to do this. With good cause mind you, but still it's a failure. If your were supposed to make a widget by Wednesday then finish the widget by Wednesday. If your done with the widget on Tuesday then mark is done. When the client comes back and says "you forgot to implement this feature we didn't tell you about" then track that as a new thing and stick a new date on it. The important part here is to show that your getting done what you say your going to get done when you say your going to do it. It's all perception, but by not putting a close (or whatever) in that column, your looking bad.

Third, try to change the words being used. I try to use "issue" and "error". Errors are things that produce error codes. And if you have a lot of these then your writing bad code. Issues are everything else. This allows "you forgot to implement a feature we didn't tell you about", to be a issue and not a bug. It still gives it importance, but does not make it sound like bad code.

Mostly what you have here is a perception failure. Your failed to set expectations and now you need to go back and do so. This can be quite difficult, but rewarding. Be careful to set expectations that you can meet.  And keep in mind that the client is not going to want to move some of his expectations after this long. Also consider hiring someone external to the project to do a code review or something of that nature. Having a third party review the situation usually helps. It has it's own downfalls, but if you written good code, having a third party agree and state so, will help the client feel better about the situation.


问:
Linking a GPL executable from proprietary .bat script
Licensing question - am I allowed to use a GPL binary executable (.exe) in my copyrighted .bat script? Namely I want to use FART command line tool (find & replace text in files) in an install script for a proprietary product. Is such use actually static or dynamic type of linking?</p>

答:
Bat files execute and do not link. </p>

<p>Yes you can execute GPLed code from non-GPLed code. The only thing you will need to do is if you distribute FART, make sure you distribute it's source code as well. See semantic A/V for a popular example. Or many video games.  As long as you give credit and don't violate the rules about distributing binaries without source your should be fine. </p>

Body:
Bat files execute and do not link.

Yes you can execute GPLed code from non-GPLed code. The only thing you will need to do is if you distribute FART, make sure you distribute it's source code as well. See semantic A/V for a popular example. Or many video games.  As long as you give credit and don't violate the rules about distributing binaries without source your should be fine.


问:
When to use [Pure] on a constructor?
I'm learning about code contracts in .NET, and I'm trying to understand the idea of pure constructors. The code contracts documentation states:

All methods that are called within a contract must be pure; that is, they must not update any preexisting state. A pure method is allowed to modify objects that have been created after entry into the pure method.

And the PureAttribute documentation states:

Indicates that a type or method is pure, that is, it does not make any visible state changes.

I understand these statements when it comes to methods, but what about constructors? Suppose you had a class like this:

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

    public Foo(int value) {
        this.Value = value;
    }
}
</code>```

This constructor obviously does affect the state of the new Foo object, but it has no other side effects (e.g. it doesn't manipulate any of the parameters or call any non-pure methods). Is this a candidate for [Pure] or not? What is the significance of placing a [Pure] attribute on a constructor, and when should I do this in my own code?

答: The object cannot be used until it is constructed in this case. Therefore the constructor is pure. If the constructor called other code, or invoked a delegate, and the other code modified the mutable property, it would not be pure. To be safer, it is better to make the property immutable.</p>

Title: When to use [Pure] on a constructor?


答:
You decorate a method with [Pure]:

If the method doesn't have side effects. For example, if the method accesses a database and modifies it or its result depends on the database, it's not pure.

And if you expect to use it in code contracts. For example, if the method is pure, but you have no intention to use it in code contracts, adding [Pure] would have no benefit and won't make your code faster.

As far as it concerns constructors, it looks like they are assumed to be pure in .NET and don't need an explicit attribute. I looked at several constructors in .NET Framework source, such as DateTime, and they don't have [Pure] attribute.

I suppose this is done for several reasons:

It may be too impractical to have to write a parameterless constructor with [Pure] attribute just to be able to use the class/struct in a contract.

Some, such as String, don't have explicit constructors.

The constructors receive special treatment even outside code contracts; for example, you're not expected to throw exceptions inside them.

[Pure] is just a convention which is here to simplify your life, but there is no actual static checking to ensure that the method decorated with this attribute is pure. void DestroyDatabase() may be decorated as being pure, and code contracts won't notice anything wrong.

Currently there is no component of Code Contracts which checks if methods declared pure are pure indeed. Thus if a programmer decorated a method with [Pure], it’s just believed.

From Code Contracts #5: Method purity

.NET Framework itself contains constructors which are not pure. For example, List<T>(IEnumerable<T> collection) is actually impure if looping through the collection has side effects.

Contracts shout be kept simple. I can easily imagine a contract such as Contract.Requires(!string.IsNullOrEmpty(name)), so there are good reasons to declare the static string.IsNullOrEmpty pure.

On the other hand, if you need a StringBuilder in order to build the string you'll check then for something by calling an instance method of your business class, you're probably misusing the contracts. That's also why StringBuilder.ToString is not marked as pure, even if it might be (is it?)

Title: When to use [Pure] on a constructor?

Body:
I'm learning about code contracts in .NET, and I'm trying to understand the idea of pure constructors. The code contracts documentation states:

All methods that are called within a contract must be pure; that is, they must not update any preexisting state. A pure method is allowed to modify objects that have been created after entry into the pure method.

And the PureAttribute documentation states:

Indicates that a type or method is pure, that is, it does not make any visible state changes.

I understand these statements when it comes to methods, but what about constructors? Suppose you had a class like this:

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

    public Foo(int value) {
        this.Value = value;
    }
}
</code>```

This constructor obviously does affect the state of the new Foo object, but it has no other side effects (e.g. it doesn't manipulate any of the parameters or call any non-pure methods). Is this a candidate for [Pure] or not? What is the significance of placing a [Pure] attribute on a constructor, and when should I do this in my own code?


问:
Passing two different types down a chain of calls because of an overload further down
I've got myself into a bit of a mess. I've got code coming from Main, through myMethod and down to OtherMethod. One of the parameters can be either an int or a string, which affects OtherMethod but none of the intervening methods.

```<code>public static void Main()
{
    myMethod(number: 10);
    myMethod(letters: "ten");
}

public static void myMethod(int number = 0, string letters = null)
{
    //long entirely shared code with calls to:
    OtherMethod(number,letters);
}

public static void OtherMethod(int number = 1, string letters = null)
{
    //Lots of shared code, embedded multiple times within this code is essentially:
    if (letters != null)
    {
        Console.WriteLine("letters!");
    }
    else
    {
        Console.WriteLine("numbers!");
    }
}
</code>```

OtherMethod cares about when I'm passing it int or string, but none of the intervening methods care. I would also find splitting OtherMethod without unnecessary code reuse very hard.

The solution I have provided works, but is probably an anti-pattern. Because, for example, a call to myMethod(10,"ten") would silently throw 10 in the bin.

Would changing it to private mymethod(int number = 0, string = null) called by public (int number) and public (string letter) for each level be a terrible idea?

I though of instead passing a class with both int and string and instructions of which to use right from the top to bottom. I suspect this is the solution. But it feels as OTT as it does OO.

My real use case is that I'm randomly generating data at the bottom of this chain and I can either provide a seed (int), or cheat and provide the data to generate (string). It occurs to me that what I'm doing may be a procedural dependency injection bodge,

答:
You are on the right track thinking you need to inject a class rather than the int and string parameters, but you actually want to inject one of two classes implementing a common interface:  one with an int specialization and one with a string specialization.

To avoid the duplication in OtherMethod, you can make that common code that calls implementation-specific helper functions as necessary.  In other words, wherever you have if (letters != null) put a call to HelperMethod().

I don't know C#, so consider this pseudocode, but it would look something like this:

```<code>public static void Main()
{
    myMethod(new IntGenerator(10));
    myMethod(new StringGenerator("ten"));
}

public static void myMethod(Generator gen)
{
    //long entirely shared code with calls to:
    gen.OtherMethod();
}

abstract class Generator {
    abstract void HelperMethod();

    public void OtherMethod()
    {
        //Lots of shared code, embedded multiple times within this code is:
        HelperMethod();
    }
}

class IntGenerator extends Generator
{
    IntGenerator(int value) {}

    void HelperMethod()
    {
        Console.WriteLine("numbers!");
    }
}

class StringGenerator extends Generator
{
    StringGenerator(string value) {}

    void HelperMethod()
    {
        Console.WriteLine("letters!");
    }
}
</code>```

Yes, this creates a lot more functions, but if you divide it up properly, they are going to be much easier to maintain.

Body:
You are on the right track thinking you need to inject a class rather than the int and string parameters, but you actually want to inject one of two classes implementing a common interface:  one with an int specialization and one with a string specialization.

To avoid the duplication in OtherMethod, you can make that common code that calls implementation-specific helper functions as necessary.  In other words, wherever you have if (letters != null) put a call to HelperMethod().

I don't know C#, so consider this pseudocode, but it would look something like this:

public static void Main()
{
    myMethod(new IntGenerator(10));
    myMethod(new StringGenerator("ten"));
}

public static void myMethod(Generator gen)
{
    //long entirely shared code with calls to:
    gen.OtherMethod();
}

abstract class Generator {
    abstract void HelperMethod();

    public void OtherMethod()
    {
        //Lots of shared code, embedded multiple times within this code is:
        HelperMethod();
    }
}

class IntGenerator extends Generator
{
    IntGenerator(int value) {}

    void HelperMethod()
    {
        Console.WriteLine("numbers!");
    }
}

class StringGenerator extends Generator
{
    StringGenerator(string value) {}

    void HelperMethod()
    {
        Console.WriteLine("letters!");
    }
}

Yes, this creates a lot more functions, but if you divide it up properly, they are going to be much easier to maintain.


问:
Alternative to Static Abstract Property/Method
Since trying to use them will cause an error what is the workaround to get the same effect as them?

My Base Class:

```<code>public abstract class IPacket
{
    public abstract int Identifier { get; set; }

    public abstract void Handle();
}
</code>```

Child Class:

```<code>public class DoSomething : IPacket
{
    public override int Identifier
    {
        get
        {
            return 1;
        }
    }

    public override void Handle()
    {
        // Do Something
    }
}
</code>```

Incoming Packet Routing:

```<code>Dictionary<Byte, IPacket> Packets = new Dictionary<byte, IPacket>
    {
        {DoSomething.Identifier, DoSomething} // <-- Not Possible
    };

Packets[ID].Handle();
</code>```

Basically I get a packet from Server which contains an Identifier. I use this identifier to find the handler for that packet from a dictionary and pass the packet to it's handler.

答:
Since you dispatch Handle on an identifier and not on packet object's class, I don't see any benefit in having Handle as a method of packet objects.

Think about some PacketProcessor that handles packets of certain type, and a Dictionary<Identifier, PacketProcessor>.


问:
Should I be using a composite key for this table?
My database is going to store words, so the Word table is the most important. The Rhyme table lists which words a particular word perfectly rhymes with. It consists of three fields:

```<code>RhymeID - primary key.
WordID - foreign key linking to Word table
Rhyme - a non key integer which refers to a different record in the Word table.
</code>```

E.g. 'cat' has WordID 009, 'bat' has WordID 014 and 'fat' has WordID 035, two records in the Rhyme table might look like this

```<code>RhymeId - WordId - Rhyme
001 - 009 (cat) - 014 (bat)
002 - 009 (cat) - 035 (fat)
</code>```

The question is, should I make WordId a primary key to form a composite key with RhymeId? Do I need it to uniquely identify each record? I have no practical experience with databases, this one is still in the planning stage.

答:
First make it clear than Rhyme is also a FK

You should do either of the following:

Make RhymeId the PK and create an composite unique index with WordID
and Rhyme so no combination of two words appears twice.

Get rid of RhymeId and make a composite PK with WordID and Rhyme

I preffer the second option because you need to keep only one index instead of two.


答:
You could use Core.Choice or a delimited union of your own liking.

If you need to pass either one or the other value, just do not allow to pass both.

Title: Passing two different types down a chain of calls because of an overload further down

Body:
I've got myself into a bit of a mess. I've got code coming from Main, through myMethod and down to OtherMethod. One of the parameters can be either an int or a string, which affects OtherMethod but none of the intervening methods.

```<code>public static void Main()
{
    myMethod(number: 10);
    myMethod(letters: "ten");
}

public static void myMethod(int number = 0, string letters = null)
{
    //long entirely shared code with calls to:
    OtherMethod(number,letters);
}

public static void OtherMethod(int number = 1, string letters = null)
{
    //Lots of shared code, embedded multiple times within this code is essentially:
    if (letters != null)
    {
        Console.WriteLine("letters!");
    }
    else
    {
        Console.WriteLine("numbers!");
    }
}
</code>```

OtherMethod cares about when I'm passing it int or string, but none of the intervening methods care. I would also find splitting OtherMethod without unnecessary code reuse very hard.

The solution I have provided works, but is probably an anti-pattern. Because, for example, a call to myMethod(10,"ten") would silently throw 10 in the bin.

Would changing it to private mymethod(int number = 0, string = null) called by public (int number) and public (string letter) for each level be a terrible idea?

I though of instead passing a class with both int and string and instructions of which to use right from the top to bottom. I suspect this is the solution. But it feels as OTT as it does OO.

My real use case is that I'm randomly generating data at the bottom of this chain and I can either provide a seed (int), or cheat and provide the data to generate (string). It occurs to me that what I'm doing may be a procedural dependency injection bodge,


答:
```<code>DoSomething newSomething = new DoSomething();
Dictionary<int, IPacket> Packets = new Dictionary<int, IPacket>
{
    { newSomething.Identifier, newSomething } // <-- Possible
};
</code>```

IPacket as an abstract class and not an interface isn't intuitive naming.

```<code>// Alternatively,
public interface IPacket
{
    int Identifier { get; }
    void Handle();
}

public class DoSomething : IPacket
{
    public int Identifier { get; set; }
    public void Handle() { }
}
</code>```

...

```<code>int id = 1;
Dictionary<int, IPacket> Packets = new Dictionary<int, IPacket>
{
    { id, new DoSomething { Identifier = id } }
};
</code>```

Title: Alternative to Static Abstract Property/Method

Body:
Since trying to use them will cause an error what is the workaround to get the same effect as them?

My Base Class:

```<code>public abstract class IPacket
{
    public abstract int Identifier { get; set; }

    public abstract void Handle();
}
</code>```

Child Class:

```<code>public class DoSomething : IPacket
{
    public override int Identifier
    {
        get
        {
            return 1;
        }
    }

    public override void Handle()
    {
        // Do Something
    }
}
</code>```

Incoming Packet Routing:

```<code>Dictionary<Byte, IPacket> Packets = new Dictionary<byte, IPacket>
    {
        {DoSomething.Identifier, DoSomething} // <-- Not Possible
    };

Packets[ID].Handle();
</code>```

Basically I get a packet from Server which contains an Identifier. I use this identifier to find the handler for that packet from a dictionary and pass the packet to it's handler.

Body:
DoSomething newSomething = new DoSomething();
Dictionary<int, IPacket> Packets = new Dictionary<int, IPacket>
{
    { newSomething.Identifier, newSomething } // <-- Possible
};

IPacket as an abstract class and not an interface isn't intuitive naming.

// Alternatively,
public interface IPacket
{
    int Identifier { get; }
    void Handle();
}

public class DoSomething : IPacket
{
    public int Identifier { get; set; }
    public void Handle() { }
}

...

int id = 1;
Dictionary<int, IPacket> Packets = new Dictionary<int, IPacket>
{
    { id, new DoSomething { Identifier = id } }
};


问:
Controlling version numbers in sprints
Traditionally software build numbers fit into the format

Major

Minor

Release

Build

Where a Major version is implemented whenever there are breaking changes, Minor when new mini features are added, Release when something is published and Build each time it's built.

I find the last two digits work really well in a CI environment, each CI build increases the Build number and each release to live increments the Release number.

However major waterfall work and breaking change developments are discouraged in more modern methodologies. We prefer to release little and often and so don't tend to make great breaking changes. Given this it's very difficult to determine when to create a new Major version.

We try to avoid making major breaking changes and so are getting very high minor/release numbers but haven't had the excuse to move up a major version yet. What criteria should be used to determine when Major and Minor builds should be made (particularly web based applications)?

I'm aware there are date style versioning but I'm interested in the Major.Minor.Build.Release only.

答:
I think some of the challenge starts with your assertion of:

Where a Major version is implemented whenever there are breaking changes

And I'm pretty sure you mean "breaking changes" in the sense of significant API changes; client / server communication changes; protocol work, etc.  "Big Stuff" (TM) in other words.

But the problem is that it's not just breaking changes that count but any significant change that counts.  "Significant" varies from application to application, which is why it's hard to be specific about what qualifies as significant.  Changing the major number should be an informal announcement to the end users that:

Something big is different

They ought to prepare or be aware that this likely won't be a trivial update

So here are a number of common reasons I have seen to update the major number:

Marketing (or development) felt like it.

Wicked cool, brand-new, big feature introduced.  Or a whole bunch of these.

Database schema underwent significant change.  Oftentimes this will force an update for the end-users.

Protocol changes.  This can included significant changes between the browser and the web server, or could be between the client and server.

Application stability has significantly improved (or worsened) and you want to change Major version to inform or warn users of the change.

Some specific amount of time has passed - this could be X months, years, whatever.

The product is now compliant with some external standard or otherwise audit-able process.

The application was forked.

Significant changes were made in supporting libraries, or which libraries could be used.

Generally speaking, you want to be able to say why you incremented the major value.  This is where building an "elevator pitch" to justify the increment can be handy.  And just like an elevator pitch that you use to sell yourself, this is a quick statement that summarizes what was big enough to merit the change.

Some additional thoughts regarding versioning...

First off, you don't have to update the Major value on a regular basis.  It may not make sense if everything that's being provided is a lot of little items.

If you feel like you're "running out of room" with the values for the other numbers, consider:

Use hexadecimal values (base 16) or another base instead of just decimal values (base 10).

Use two or more digits within each value.  So you'd have M.mm.rr.bbb for example.

Title: Controlling version numbers in sprints


答:
I would go much deeper than Karl and convert the whole myMethod and OtherMethod into a class. Then you can use inheritance and abstract method to differentiate the cases.

```<code>public abstract class Generator
{
    public void Invoke()
    {
        //long entirely shared code with calls to:
        OtherMethod();
    }

    protected abstract void OtherMethod();
}

public class IntGenerator : Generator
{
    private int _number;
    public IntGenerator(int number)
    {
        _number = number;
    }

    protected override void OtherMethod()
    {
        Console.WriteLine("numbers!");
    }
}

public class StringGenerator : Generator
{
    private string _letters;
    public StringGenerator(string letters)
    {
        _letters = letters;
    }

    protected override void OtherMethod()
    {
        Console.WriteLine("letters!");
    }
}

class Program
{
    static void Main(string[] args)
    {
        new IntGenerator(10).Invoke();
        new StringGenerator("ten").Invoke();
    }
}
</code>```

The major advantage is that in your code, you can just use Generator and swap around whenever you are using Int or String without need to change the code.

Body:
I would go much deeper than Karl and convert the whole myMethod and OtherMethod into a class. Then you can use inheritance and abstract method to differentiate the cases.

public abstract class Generator
{
    public void Invoke()
    {
        //long entirely shared code with calls to:
        OtherMethod();
    }

    protected abstract void OtherMethod();
}

public class IntGenerator : Generator
{
    private int _number;
    public IntGenerator(int number)
    {
        _number = number;
    }

    protected override void OtherMethod()
    {
        Console.WriteLine("numbers!");
    }
}

public class StringGenerator : Generator
{
    private string _letters;
    public StringGenerator(string letters)
    {
        _letters = letters;
    }

    protected override void OtherMethod()
    {
        Console.WriteLine("letters!");
    }
}

class Program
{
    static void Main(string[] args)
    {
        new IntGenerator(10).Invoke();
        new StringGenerator("ten").Invoke();
    }
}

The major advantage is that in your code, you can just use Generator and swap around whenever you are using Int or String without need to change the code.


问:
Rules and advice for logging?
In my organization we've put together some rules / guildelines about logging that I would like to know if you can add to or comment.

We use Java but you may comment in general about loggin - rules and advice

Use the correct logging level

ERROR: Something has gone very wrong and need fixing immediately

WARNING: The process can continue without fixing. The application should tolerate this level but the warning should always get investigated.

INFO: Information that an important process is finished

DEBUG. Is only used during development

Make sure that you know what you're logging.

Avoid that the logging influences the behavior of the application

The function of the logging should be to write messages in the log.

Log messages should be descriptive, clear, short and concise.

There is not much use of a nonsense message when troubleshooting.

Put the right properties in log4j

Put in that the right method and class is written automatically.

Example:

Datedfile -web

```<code>log4j.rootLogger=ERROR, DATEDFILE
log4j.logger.org.springframework=INFO
log4j.logger.waffle=ERROR
log4j.logger.se.prv=INFO
log4j.logger.se.prv.common.mvc=INFO
log4j.logger.se.prv.omklassning=DEBUG

log4j.appender.DATEDFILE=biz.minaret.log4j.DatedFileAppender
log4j.appender.DATEDFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.DATEDFILE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%C{1}.%M] - %m%n

log4j.appender.DATEDFILE.Prefix=omklassning.
log4j.appender.DATEDFILE.Suffix=.log
log4j.appender.DATEDFILE.Directory=//localhost/WebSphereLog/omklassning/
</code>```

Log value.

Please log values from the application.

Log prefix.

State which part of the application it is that the logging is written from, preferably with something for the project agreed prefix e.g. PANDORA_DB

The amount of text.

Be careful so that there is not too much logging text. It can influence the performance of the app.

Loggning format:

-There are several variants and methods to use with log4j but we would like a uniform use of the following format, when we log at exceptions:

logger.error("PANDORA_DB2: Fel vid hämtning av frist i
TP210_RAPPORTFRIST", e);

In the example above it is assumed that we have set log4j properties so that it automatically write the class and the method.

Always use logger and not the following:

System.out.println(), System.err.println(), e.printStackTrace()

If the web app uses our framework you can get very detailed error information from EJB, if using try-catch in the handler and logging according to the model above:

In our project we use this conversion pattern with which method and class names are written out automatically . Here we use two different pattents for console and for datedfileappender:

```<code>log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.appender.DATEDFILE.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
</code>```

In both the examples above method and class wioll be written out. In the console row number will also be written our.

toString()

Please have a toString() for every object.
EX:

```<code>@Override
public String toString() {
  StringBuilder sb = new StringBuilder();
  sb.append(" DwfInformation [ ");
  sb.append("cc: ").append(cc);
  sb.append("pn: ").append(pn);
  sb.append("kc: ").append(kc);
  sb.append("numberOfPages: ").append(numberOfPages);
  sb.append("publicationDate: ").append(publicationDate);
  sb.append("version: ").append(version);
  sb.append(" ]");
  return sb.toString();
}
</code>```

instead of special method which make these outputs

```<code>public void printAll()
{
    logger.info("inbet: " + getInbetInput());
    logger.info("betdat: " + betdat);
    logger.info("betid: " + betid);
    logger.info("send: " + send);
    logger.info("appr: " + appr);
    logger.info("rereg: " + rereg);
    logger.info("NY: " + ny);
    logger.info("CNT: " + cnt);
}
</code>```

So is there anything you can add, comment or find questionable with these ways of using the logging? Feel free to answer or comment even if it is not related to Java, Java and log4j is just an implementation of how this is reasoned.

答:
Logging is most of the time a cross cutting concern. Java alone is not sufficient expressive to make you able to seperate the logging from the your actual business logics. This means you cannot for example just take one method and put it into another project but you you have to remove and adjust all your logging before you do. And that is just the tip of the iceberg.

To prevent that and other issues when mingling logging and "real" business logics you should regard using aspect oriented programming. For Java the most used framework would be AspectJ. There is this youtube video from google tech talks that explains AspectJ and its uses beyond logging pretty well. You will find many examples for logging yourself of course here on stackexchange too.

Title: Rules and advice for logging?


问:
Should I persist notification before or after publishing it through Redis pub/sub?
I'm implementing a mechanism to notify a group of users about newly inserted blog comments.
The architecture uses the Redis Pub/Sub mechanism.

By definition, the pub/sub mechanism aims to propagate message to the right subscribers, without storing/persisting anything.

Although blog comments are obviously persisted in DB, I also expect all notifications to be sent to be persisted in order to be retrieved at any time by an offline user that gets logged again.
Of course, Redis could have persistent messages, but the cost for that is pretty high.

I use a distinct main database, let's take for the example MySql.
Currently, the workflow is:

A blog comment posted by a user is handled by my backend and firstly stored in DB.

An event is raised, let's call it "CommentedBlogEvent", that triggers a worker aiming to detect all the targeted user of the comment.

Assuming that 10 users are target of the comment, I insert 10 "notification rows" in my database associating the commentId and the targeted userId, each specific to a user since it would have a flag read/unread.

Then, once all notifications have been persisted, I use Redis Pub/Sub to trigger subscribers aiming to push results to the concerned online clients (through WebSockets for instance).

The "issue" is that the process could be slow because of the step 3.

Would it be tolerated to make the step 4 before the step 3, meaning before persisting it in DB, since a potential data loss isn't dramatic in my case (non-financial data etc)?

Advantage: Client gets result more quickly.

Drawback: User could receive a notification that failed to be stored in background, leading to a missing notification when user refreshes the page.

What is the best way to handle this case, while keeping my main database as the notifications store?

答:
The "issue" is that the process could be slow because of the step 3.

You may want to use a pipeline: While step 3 is still inserting notifications, have step 4 start process notifications that are already inserted. You may have to redesign how step 3 works, e.g. by splitting up the users into batches.

Would it be tolerated to make the step 4 before the step 3, since a potential data loss isn't dramatic in my case (non-financial data etc)?

Whether data loss is dramatic or not very much depends on how users perceive this loss, and how often it happens. If you tell your users "never miss a blog comment" and then fail to deliver notifications reliably, that could still be quite dramatic. If you fail to deliver 1 ppm that's probably not too bad, if you fail to deliver 500'000 ppm, well that's just bad design.


答: It is definitely okay and I would encourage you to have several classes in one file as long as they are realated. In general your classes should stay short and concise and you should rather split up behaviour in two or more classes than build huge monolithic ones. When writing several small classes it is really necessary and helpful to keep those that are related in the same file.</p>

Title: Is it considered Pythonic to have multiple classes defined in the same file?

Body:
In working with python for the first time, I've found that I end up writing multiple classes in the same file, which is opposed to other languages like Java, which uses one file per class.

Usually, these classes are made up of 1 abstract base class, with 1-2 concrete implementations who's use varies slightly. I've posted one such file below:

```<code>class Logger(object):

    def __init__(self, path, fileName):
        self.logFile = open(path + '/' + filename, 'w+')
        self.logFile.seek(0, 2)

    def log(self, stringtoLog):
        self.logFile.write(stringToLog)

    def __del__(self):
        self.logFile.close()

class TestLogger(Logger):

    def __init__(self, serialNumber):
        Logger.__init__('/tests/ModuleName', serialNumber):

    def readStatusLine(self):
        self.logFile.seek(0,0)
        statusLine = self.logFile.readLine()
        self.logFile.seek(0,2)
        return StatusLine

    def modifyStatusLine(self, newStatusLine):
        self.logFile.seek(0,0)
        self.logFile.write(newStatusLine)
        self.logFile.seek(0,2)

class GenericLogger(Logger):

    def __init__(self, fileName):
        Logger.__init__('/tests/GPIO', fileName):

    def logGPIOError(self, errorCode):
        self.logFile.write(str(errorCode))
</code>```

As seen above, I have a Logger base class, with a couple of implementation differences below that.

The Question:
Is this standard for python, or for any language? What problems could arise from using this implementation if any?

Please note: I'm not really looking for guidance on this specific file, but in a more general sense. What if the classes ended up being 3-5 moderately complex methods? Would it make sense to split them then? Where is the cutoff for saying you should split a file up?


问:
Compiler warnings and errors
I come from a C# background before my existing role.  I am developing a VB.NET app.  The code I inherited had option strict set to off and all other directives set to 'None'.  I have recently switched option strict on and corrected all the errors.  It will take me about one day to correct all the warnings.  I am trying to decide whether this is time well spent.

The application is mature and is working very well.  What is the guidance for setting option strict to ON and correcting warnings.  I assume that you should not ignore them.

However, I read online today (I think it was on here) were one questioner said he/she never bothers with warnings.  Surely this is wrong?

答:
It is a subjective issue. On every new project we (myself and some colleagues I know) start, we set warnings to compile errors by default. We end up with a clean code base, easy solution. (Plus, we also enable FxCop, StyleCop issues as errors, very low cost if you do it from the beginning).

Every warning has some impact on quality, maintainability, performance, security etc. There is no easy recommendation of "fix all" or "ignore all". The primary reason that these are warnings and not errors or not reported is primarily because a decision is not easy to make in all situations.

In the code base that has already been developed, it is usually a slow process. This is what I would do:

I would typically evaluate the impact of a warning.

If it's a performance warning in a piece of code that is not going to be hit too often, I'll ignore.

But if I am using a method that is obsolete, it may have a security impact, or eventually, the underlying class library might eventually break me.

Then I would typically evaluate the cost.

If it's an "unused variable", I'll fix it. If it's a thousand unused variables, I'll ignore with an understanding that it'll take me a few hours to fix those, and the impact is on code readability and perhaps maintenance.

Other warnings can be expensive, e.g. using an obsolete method, and changing that usage requires a serious code rewrite.

Based on the above two metrics (which really feeds into a cost/benefit analysis), I'll fix what makes sense immediately.

For the rest, the rule would typically be to fix the warnings when someone touches the code base, i.e. when the code is touched, one cannot say "I can leave it in a crappy state because I found it so." :-)

This works in most cases. What works for you will depend on your experience. For every warning, you can do an evaluation, and if you need others' opinions, post on stackoverflow probably to get recommendations. I am sure many issues have already been discussed there.

Title: Compiler warnings and errors


问:
REPL - Do You Find It Useful?
Recently I started learning Clojure and downloaded Clojure-Box for Windows which came with SLIME and have been fiddling around with Clojure using the REPL mode. Now, I have starting learning many languages that have REPL available (F#, Python, Haskell) but have never used it until I started with Clojure and I realized how much of a help it is.

I was wondering how many people use REPL for the languages that have them available. If you don't use them, what is your reasoning not to? If you do use them, do you use them for testing code or just for learning languages?

答: I find the REPL very useful, especially when integrated with the text editor as in Clojure-Box or Lisp-Box. The big win is finding out right away if what you're trying to do will work properly. You can execute and test each function as you type it in instead of waiting for the entire application to compile. </p>

ContentLicense: CC BY-SA 2.5

Title: REPL - Do You Find It Useful?


问:
Should we live by using Suhosin with PHP?
A lot of my security experienced friends have told me that I need to code my web applications for working under the Suhosin PHP patch, Suhosin being "an advanced protection system for PHP installations [...] designed to protect servers and users from known and unknown flaws in PHP applications". Sense stating that feat, I have had to rewrite quite a bit of of my functions and classes.

Is this the new standard of making secure web applications so that it is harder to exploit and compromise? Is Suhosin now a common requirement for web development in PHP?

答:
The description on the Suhosin website is pretty clear, emphasis mine:

If you are using PHP only for your own server and only for your own scripts and applications, then you can judge for yourself, if you trust your code enough. In that case you most probably don’t need the Suhosin extension. [...] Even PHP core programmers are writing insecure code from time to time, because they did not know about a PHP pitfall.

Suhosin is one of the ways to mitigate risks related to buffer overflows and similar vulnerabilities. It's not the only way, and it won't magically make your application 100% secure and bug-free.

Should every PHP programmer use it? No, because it's an overkill. Personally, I would rather convince every PHP programmer to read and understand OWASP top ten vulnerabilities, and when I read PHP-tagged questions on Stack Overflow for a few minutes, I only hope every PHP programmer will learn what SQL Injection is, and only that would be a big step.

For small projects, it doesn't matter. If they are written by a guy who knows what SQL Injection is, great. It's just that there are more important things to do, such as getting the job done or finding actual customers.

Large projects are often written by experienced developers who know their stuff and know what are the vulnerabilities and how to avoid them. An additional pair of eyes such as Suhosin won't hurt, but the team has to watch all the pros and cons before adopting it, especially since it may be quite redundant with other techniques. I would prefer my code to be reviewed by a security expert rather than to rely on a tool I didn't even knew the name half an hour ago.

Medium-scale projects are where Suhosin may be interesting. Those ones may not be able to afford security experts and skillful developers, so any free tool, would it be a static checker or an extension like Suhosin, may help. At the same time, I would understand the hassle to deploy an additional extension to production servers.

Using such extension can also give a false sense of security, especially when you read things like:

Always keep in mind that you are not only protecting yourself and your users, but also other people on the internet, that might get attacked by your server after it has been turned into a (Spam-/DDOS-)attack drone.

Here is a raw and sloppy estimate of the sources of severe security risks on my customers' servers (non business-critical small to small-to-medium scale web apps):

70%: The server is not maintained (example: four years' old version of PHP, never patched despite critical issues discovered since then).

15%: I or my team introduced a bug in the web application or used a third-party library which had a bug I haven't noticed.

10%: The server hosts FTP, SMTP, DNS, Active Directory, SQL Server 2000, SQL Server 2005, SQL Server 2008 R2, Sharepoint, IIS, Apache and a dozen of other services. Given that nobody knows how to configure the firewall, it was disabled. One day, when this domain controller is hacked, nobody has even the slightest clue what was used by the attacker.

1%: There is an exploit in the latest version of PHP, operating system or a popular framework (see Zero-day attack).

4%: Something else.

Suhosin will help here in maximum 15% of cases, but will give a feeling that I don't have to deal with 95% of possible issues.

The same false sense of security may lead to bigger problems:

If you are not only running your own PHP scripts but are also hosting 3rd party PHP applications for yourself or even for possible customers, then you cannot trust the code quality of the PHP applications you use.

If I don't trust third-party code, I don't use it. Not on my servers. If it's code which cannot be reviewed, such as code written by customers themselves, then it should run in a sandbox anyway, with very restrictive permissions.


问:
How bad is it calling println() often than concatenating strings together and calling it once?
I know output to the console is a costly operation. In the interest of code readability sometimes it is nice to call a function to output text twice, rather than having a long string of text as an argument.

For example how much less efficient is it to have

```<code>System.out.println("Good morning.");
System.out.println("Please enter your name");
</code>```

vs.

```<code>System.out.println("Good morning.\nPlease enter your name");
</code>```

In the example the difference is only one call to println() but what if it's more?

On a related note, statements involving printing text can look strange while viewing the source code if the text to print is long. Assuming the text itself can't be made shorter, what can be done? Should this be a case where multiple println()calls be made? Someone once told me a line of code shouldn't be more than 80 characters (IIRC) so what would you do with

```<code>System.out.println("Good morning everyone. I am here today to present you with a very, very lengthy sentence in order to prove a point about how it looks strange amongst other code.");
</code>```

Is the same true for languages such as C/C++ since each time data is written to an output stream a system call must be made and the process must go to kernel mode (which is very costly)?

答:
While the performance is not really an issue here, the bad readability of a bunch of println statements points to a missing design aspect.

Why do we write a sequence of many println statements? If it were just one fixed text block, like a --help text in a console command, it would be much better to have it as a separate ressource and to read it in and write it to the screen on request.

But usually it is a mixture of dynamic and static parts. Let's say we have some bare order data on the one hand, and some fixed static text parts on the other hand, and these things have to be mixed together to form an order confirmation sheet. Again, also in this case, it is better to have a separate ressource text file: The ressource would be a template, containing some kind of symbols (placeholders), which are replaced at runtime by the actual order data.

The separation of the programming language from the natural language has many advantages - among these is internationalization: You might have to translate the text if you want to become multilangual with your software. Also, why should a compile step necessary if you only want to have a textual correction, say fix some misspelling.

OwnerDisplayName: Celeritas


问:
How does datomic handle "corrections"?
tl;dr

Rich Hickey describes datomic as a system which implicitly deals with timestamps associated with data storage

from my experience, data is often imperfectly stored in systems, and on many occasions needs to retroactively be corrected (ie, often the question of "was a True on Tuesday at 12:00pm?" will have an incorrect answer stored in the database)

This seems like a spot where the abstractions behind datomic might break - do they? If they don't, how does the system handle such corrections?

Rich Hickey, in several of his talks, justifies the creation of datomic, and explains its benefits.

His work, if I understand correctly, is motivated by core the insight that humans, when speaking about data and facts, implicitly associate some of the related context into their work(a date-time). By pushing the work required to manage the implicit date-time component of context into the database, he's created a system which is both much easier to understand, and much easier to program. This turns out to be relevant to most database programmers in practice - his work saves everyone a lot of time managing complex, hard to produce/debug/fix, time queries.

However, especially in large databases, data is often damaged/incorrect (maybe it was not input correctly, maybe it eroded over time, etc...). While most database updates are insertions of new facts, and should indeed be treated that way, a non-trivial subset of the work required to manage time-queries has to do with retroactive updates.

I have yet to see any documentation which explains how such corrections, or retroactive updates, are handled by datomic; from my experience, they are a non-trivial (and incredibly difficult to deal with) subset of time-related data manipulation that database programmers are faced with.

Does datomic gracefully handle such updates? If so, how?

答:
This is to respond to blueberryfields' comment @ Oct 3 '13 at 4:28

The question the built in time stamp will answer is what did I enter on Tuesday at 12, not what do I now believe the entered value to be on Tuesday at 12.

I believe this is how you should use Datomic. The built in time stamp can help you know when a bad input was made so you can make a correction to it. Not to correct what you thought in the past.

Title: How does datomic handle "corrections"?


答: Oh yes, I find them very useful. They're nice for testing out a few lines of code, to see if something really works the way you expect it to. Many languages with REPLs also make use of in-code documentation, so it can be really easy to look up an API for a class or module via the REPL.</p>

Title: REPL - Do You Find It Useful?

Body:
Recently I started learning Clojure and downloaded Clojure-Box for Windows which came with SLIME and have been fiddling around with Clojure using the REPL mode. Now, I have starting learning many languages that have REPL available (F#, Python, Haskell) but have never used it until I started with Clojure and I realized how much of a help it is.

I was wondering how many people use REPL for the languages that have them available. If you don't use them, what is your reasoning not to? If you do use them, do you use them for testing code or just for learning languages?


答:
I don't think having a bunch of printlns is a design issue at all. The way I see it is that this can clearly be done with static code analyzer if it is really a problem.

But it is not a problem because most people don't do IOs like this. When they really need to do lot of IOs, they use buffered ones (BufferedReader, BufferedWriter, etc..) when the input is buffered, you will see that the performance is similar enough, that you don't need to worry about having a bunch of println or few println.

So to answer the original question. I would say, not bad if you use println to print a few things out as most people would use println for.

Title: How bad is it calling println() often than concatenating strings together and calling it once?

Body:
I know output to the console is a costly operation. In the interest of code readability sometimes it is nice to call a function to output text twice, rather than having a long string of text as an argument.

For example how much less efficient is it to have

```<code>System.out.println("Good morning.");
System.out.println("Please enter your name");
</code>```

vs.

```<code>System.out.println("Good morning.\nPlease enter your name");
</code>```

In the example the difference is only one call to println() but what if it's more?

On a related note, statements involving printing text can look strange while viewing the source code if the text to print is long. Assuming the text itself can't be made shorter, what can be done? Should this be a case where multiple println()calls be made? Someone once told me a line of code shouldn't be more than 80 characters (IIRC) so what would you do with

```<code>System.out.println("Good morning everyone. I am here today to present you with a very, very lengthy sentence in order to prove a point about how it looks strange amongst other code.");
</code>```

Is the same true for languages such as C/C++ since each time data is written to an output stream a system call must be made and the process must go to kernel mode (which is very costly)?


问:
w3c library license: does it prevent the inclusion in/distribution with paid software?
From W3C Software Notice and License:

Permission to copy, modify, and distribute this software and its documentation, with or without modification, for any purpose and without fee or royalty is hereby granted

My app depends on the xml-apis 1.4.01 library that in turn includes W3C software and I need to distribute it along with my non-free app. I am not explicitly charging for the included xml-apis/W3C components. Does the stated license statement exclude such a paid distribution?

Don't answer if you are not aware of the GPL linking exception.

答:
This licence does not itself exclude a paid distribution of any kind. It is provided to you without fee or royalty, but imposes no restriction on whether you in turn do or do not charge fees or royalties for your software.

This licence is also unaffected by any other licences that may be in effect for other parts of your software. It is plain, simple and very clear. No court would have trouble with it.

Please note that this is not the same as placing software in the public domain. The entity granting this licence retains copyright, and might provide the same software to others on different terms. You do not gain the right to trade in the software, or to claim that you wrote it. You can only copy modify or distribute it.

Please note also that compatibility with other licences, such as the GPL with or without exclusions, is not guaranteed. While your rights to use this software are certain, the inclusion of this software in a merged work could impair your rights to use other software provided under other terms. If that issue underlay your question, you should edit it to make it clear which other licences you are using and what concerns you may have.


问:
What UML diagram should be used for modelling permissions/users/files in Linux?
If I am planning a structure for support testing in Linux, a structure that will contain packages, such files as shell and build scripts, app configurations, DBs, sources, tests and jars for to be managed, applications for be managers, users, permissions, etc., what diagram could be used for it? Just now I am using the Component Diagram with some stereotyping, but it is not at all convenient in the part of permissions/users stuff. There are such diagrams as RBAC, but they are not UML, and it remains unclear how to combine them.

An example picture and/or a real experience description would be highly appreciated. But any fresh thought will be useful, too.

答:
I donot think that there is a good uml-diagram type to model this.

The best (but in my opinion still inapropriate) diagram i can think of is a use case diagram where the Actor can be considered as a role with certain permissions.

Use_Casees are from business-point-of-view while asking for "linux" or "file" is asking from technical-point-of-view.


问:
How to handle enums in an indirection with functionpointers at ANSI-C?
Moinsen,

I am somehow stucked in a design problem. Language is ANSI-C.

Lets assume we have a tinkerbox of software-modules:

one module for the logic Logic

(at least) one module doing some logging Logger

two modules, both giving a "frame" to let the program run, lets say

one with a GUI

one for commandline

...

Therefore, the same logic could used in a comandline- and a graphic-version of the software. The Logic has to log some errors but should not know anything about the specific logger as it could be dependent on the "frame". It is obvious to give Logic a function pointer that has to be filled by the frame to bind the used Logger to the Logic.

At Logging-Module (all code Pseudo-ANSI-C):

```<code>    void Logger_Log(char *sLogText)
    {
      //do some stuff
    }
</code>```

At Logic-Module:

```<code>    void Logic_PseudoLog(char *sLogText)
    {
      printf(sLogText);
    }

    void(* Logic_Log)(char *sLogText) = &Logic_PseudoLog;

    void Logic_SetLogger(void(* LogFct)(char *sLogText))
    {
      Logic_Log = LogFct;
    }
</code>```

At GUI/Cmd-Line:

```<code>    #include "Logger.h"
    #include "Logic.h"
    Logic_SetLogger(&Logger_Log);
</code>```

Now I want to introduce different severity levels for logging and implement them as an enum in Logger:

```<code>    //Logger.h:
    typedef enum {
      DEBUG,
      INFO,
      ERROR
    } teLogLevel;

    void Logger-Log(char *sLogText, teLogLevel eLevel);
</code>```

And here the problem rises: The function-pointer at Logic needs to have the correct signature. To do so, it has to know about teLogLevel. Therefore Logic has to know about the Logger, exactly the case I wanted to avoid with the indirection in the first place.

```<code>    #include "Logger.h"
    void(* Logic_Log)(char *sLogText, teLogLevel eLevel);
</code>```

The situation as layed out is just an example. Please don't solve it by saying something like "use int instead of enum" or "build three functions for the levels". The bottemline question is:

How to handle enums in an indirection with functionpointers at ANSI-C?

How to "inject" enums into a module, that should not now about the origin of the enums?

答:
Logic.h declares a function to set the logger function: Logic_SetLogger(), in order to use it.

Therefore, Logic.h must know the prototype of the logger function, whatever Logger.h is, i.e., in the most generic way possible.

This is already the case with the first argument: a pointer to a char.

For the second argument, I see two alternatives:

The usual way to handle it is to use an int, which is the generic form of an enum. Representing an error level with an int is very common among C developers.

In your case, not wanting an int, you need to use an enum type in the prototype definition of the logger function (which is in Logic.h as the argument of Logic_SetLogger()). Therefore, Logic.h needs to define the enum type as well.

In my opinion, defining error levels in Logic.h is not a good design choice.


问:
Why shouldn't you develop on production database?
I need help with organizing my arguments for why it's MADNESS to develop against production data.

Backstory: I started working here six months ago and I noticed we're developing directly against production data. The codebase is local, but the database we're connected to is live data! So i have to be super careful constantly when doing update/store operations, so that I don't break anything.

We have an annual software meeting soon and I want to raise my concerns, and come loaded with arguments but I have a really hard time coming up with good solid points to something that's should be obvious as this. It's as if they would ask me to come up with arguments to why I need to breathe.

My Question: What arguments are there for NOT developing on production database directly?

答:
So i have to be super careful constantly when doing update/store operations, so that I don't break anything.

What if you are not super careful and make a mistake?

Even when removing the potential of destroying/losing your production data (for example by working on a copy created from your daily backup), there is also the problem of securing sensitive data. Should developers really have access to that? This may even be illegal if this is for example medical data.

OwnerDisplayName: Weblurk

OwnerDisplayName: Thilo


问:
What is the one bit of computer science theory I should know?
Speaking as someone with an Electronic Engineering rather than Computer Science degree, what is the one bit of computer science I should know to make me a better real world programmer?

(By real world I mean something I'm going to use and benefit from in my day to day job as a programmer - for instance I'd suggest understanding database normalisation is of more practical use than understanding a quick sort for which there are lots of libraries).

答:
You should know enough automata theory to be able to know where the problem you're dealing with falls in the hierarchy of formal languages. From that, you can figure out a few important practical uses, like why you shouldn't use a REGEX to parse HTML (HTML needs a context free grammar to describe it), and why it takes so much longer to compile C++ as opposed to Java or C# (C++ requires a Turing machine, while Java and C# can be described with context free grammars).

The most important tiers of formal languages are, from weakest to strongest:

Languages that can be parsed by a finite automata, or a REGEX (REGEX implementations with backreferences are more powerful than this category, but they still can't parse everything in category 2)

Languages that can be parsed by an automata with stack memory, or a context-free grammar.

Languages that can be parsed by a Turing machine, or an automata with random access memory.