问:
Should I have an object as attribute or primitive id?
I am wondering which principle should I use. Here is my situation.

I have a class named TravelOffer. This class looks like this:

```<code>public class TravelOffer
{
    private final long id;

    private final StartZone startZone;
    private final EndZone endZone;
    private final List<Waypoint> waypoints;

    private final Period startOff;

    private final User travelCreator;
    private final List<User> participantsList;

    private final TravelExtras travelExtras;

    private final CandidateApprovement candidateApprovement;

    private int numberOfSeats;

    private double pricePerPerson;

    private Luggage luggage;

    private boolean additionalLuggageTransport;

    private String additionalDescription;
}
</code>```

As u see there are the following attributes:

User tavelCreator and List<User> participantsList

What I am wondering is should it be like this or simply to replace the User object with an String userId and then from a singleton class to get the User object which will be in a Hashmap?

答: It's probably best to stick with what you have, i.e. as a member variable of type User. Singletons are usually best avoided as they introduce global state. At the moment your class is a bean with no accessors or business logic, if we assume that you're going to add some business logic at some point then you'll want to test it, having the user as an (injectable) object will allow you to better unit test your class using stubs or mocks. Also this kind of functionality it typically backed by a database, you'll be in a better position to model your class graph to a database using ORM such as Hibernate if you maintain the member object. Hope that makes sense?</p>


问:
Code that converts a value into a different representation, then converts it back to where it started is bad, but how?
I was reading an article about bad programming practices.

It mentioned -

"Yo-Yo code" that converts a value into a different representation, then converts it back to where it started (eg: converting a decimal into a string and then back into a decimal, or padding a string and then trimming it)

I don't understand why the particular example he gives is a bad way to write programs.  It seems okay to me to convert back if the situation requires it so that the value can be used.

Can anyone explain more about this?

答:
It's bad for three major reasons:

It shows you haven't thought about what type/format the variable should actually be but are instead converting it to what you need at that moment. This shows lack of design thought.

It's probably wasteful. You are almost certainly wasting cycles, and lines of code, doing conversions that don't need to be there. This will make your code slower and more bloated than it needs to be.

Type conversions are prone to subtle errors. By dotting these conversions through your code you are increasing the likelihood of error.

I suspect reason 1 is the reason that your source was thinking of based on the context in which it was mentioned.

ContentLicense: CC BY-SA 3.0


问:
Implements > extends, but what about variables?
It's preferable to write programs that depend on interfaces rather than on superclasses, but what if you want a class to have certain variables? Sometimes you want a class to implement a certain variable. (For example, imagine you have a datasource interface, and want all classes to implement a "String user").

In this case, I can see making an abstract class "datasource", which other classes could then extend. But this means they can't extend another class anymore, due to no multiple inheritance in Java.

So, to conclude, if I would have the above scenario, should I rethink my design, or is there a pattern I don't know about that I could follow to achieve the interface-with-variable design?

答:
The very fact of asking whether you need to rethink your design indicates that you need to rethink it.

Result of your rethinking should be that you either (1) redesign the code so that it follows general practice for objects to expose behavior, not data, or (2) identify it as exceptional case where deviation of general norm is clearly justified (eg Data Transfer Object).

Technical way to make field usage enforced by interface is explained in this answer to prior question:

...Here you find a detailed example how to replace inheritance by delegation. This approach is so common, there is even an Eclipse refactoring exactly for this purpose

Applied to your case, above approach could look as follows.

First, you create a class (plain class, nothing special) with desired field(s):

```<code>public class Data {
    private String user;
    public void setUser(String user) { this.user = user; }
    public String getUser() { return user; }
}
</code>```

Next, you define the interface that allows to delegate to above class:

```<code>public interface DataSource {
    public Data delegate();
    //... other methods here
}
</code>```

As a result, any object implementing DataSource interface will be also forced to provide Data functionality to work with user String.

Worth reminding once again that you better do so only if this is clearly justified - besides already mentioned issue of exposing data instead of behavior, this also goes against the Law Of Demeter.

Body:
The very fact of asking whether you need to rethink your design indicates that you need to rethink it.

Result of your rethinking should be that you either (1) redesign the code so that it follows general practice for objects to expose behavior, not data, or (2) identify it as exceptional case where deviation of general norm is clearly justified (eg Data Transfer Object).

Technical way to make field usage enforced by interface is explained in this answer to prior question:

...Here you find a detailed example how to replace inheritance by delegation. This approach is so common, there is even an Eclipse refactoring exactly for this purpose

Applied to your case, above approach could look as follows.

First, you create a class (plain class, nothing special) with desired field(s):

public class Data {
    private String user;
    public void setUser(String user) { this.user = user; }
    public String getUser() { return user; }
}

Next, you define the interface that allows to delegate to above class:

public interface DataSource {
    public Data delegate();
    //... other methods here
}

As a result, any object implementing DataSource interface will be also forced to provide Data functionality to work with user String.

Worth reminding once again that you better do so only if this is clearly justified - besides already mentioned issue of exposing data instead of behavior, this also goes against the Law Of Demeter.


问:
Why are floating point numbers used often in Science/Engineering?
While investigating the accuracy of floating point numbers, I've seen in a few places a statement similar to

"float and double are (designed for/used often in) engineering and scientific calculation"

From my understanding, the strength of floats and doubles are the amount of memory they use for their (good, but not perfect) precision.

I feel like I'm almost getting an understanding from this answer

"floating point numbers let you model continuous quantities"

I still am not convinced I understand. Engineering and Science both sound like fields where you would want precise results from your calculations, which, from my understanding, floating points do not give. I'm also not sure I follow what a "continuous quantity" is, exactly.

Can somebody expand on this explanation and perhaps give an example?

答:
I think this can be answered by addressing what application float/double data types are not suitable for.

When you need to make sure that you can represent a number accurately with a specific number of digits, then floating point numbers are inappropriate, because they represent the numbers as powers of 2, instead of powers of 10, as is how we represent numbers in the real world.

So one domain where floating point data types should not be used is that of finance*. For the core system of e.g. a bank, it would be completely unacceptable if an amount that should have been $100000.01 suddenly becomes $100000.00 or $100000.02.

Such a problem could easily occur when using floats, especially if the number was the result of one or more calculations, e.g. calculating the sum of all transactions in an account.

Engineering and scientific calculation are domains where these relatively small rounding errors are acceptable. Users are normally aware that all numbers have a limited precision, and they often work with a number of significant digits. But most importantly they have a well defined relative precision, i.e. they have provide the same number of significant digits, both for very large numbers, and for very small numbers.

* I did once work on a financial application where floats had been used to represent values, and as a consequence, rounding errors were introduced. Fortunately, this specific bug wasn't critical at all, the users did complain about calculation errors in the program. And this led to a different, far worse, effect: the users started loosing faith in the system.


问:
issues about Spring initialization in different environment
I have some questions about spring's initialization in different environment.

1. In web container context, such as tomcat.

I knew that spring can be  initialized by declaring

org.springframework.web.context.ContextLoaderListener in <listener-class> field.

It will be initialized automatically when tomcat is started. (I think this is right :-）  )

2. In JUnit context

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:appContext.xml")
</code>```

annotations can be used to initialize the Spring context.

Under these two cases, we can use such as

```<code>@Autowired
private ServiceDao serviceDao;
</code>```

to use the serviceDao, and  we almost never used the ApplicationContext.getBean() method.

3. In a common J2SE environment

Should I must initialize the spring context manually,

```<code>ApplicationContext appContext = new FileSystemXmlApplicationContext(xx.xml)
</code>```

and then use appContext.getBean(XX) to get the bean?

in this case, can @Autowired be used?

How to do this?

Updated:
I try the spring-boot, I think the variable can be autowired, because the class is annotated with @Component， and with the @ComponentScan in main class, the variable can be autowired.

But I used spring xml before, and I have some injection like this, I don't know how to autowire the variable.

```<code><bean id="XXXMap" class="com.xx">
     <property name="handlerMap">
        <map>
            <entry key="XXX" value="YYY"/>
        </map>
    </property>
</bean>
</code>```

use the @component, I believe XXXMap can be autowired, but how the map is initialized?

答:
Yes, you can use @Autowired no matter how you create the application context.

There are several ways to create an application context in a standalone application. You can of course still use the traditional XML configuration files but an alternative option worth considering is spring-boot. It allows you to create completely annotation driven applications that mostly rely on conventions over configuration. Bootstrapping a simple standalone application reduces to:

```<code>@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Main implements CommandLineRunner {

    @Autowired
    private UserService userService;

    public void run(String... args) throws Exception {
        System.out.println(userService.findUser(42L));
    }

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

}
</code>```

Body:
Yes, you can use @Autowired no matter how you create the application context.

There are several ways to create an application context in a standalone application. You can of course still use the traditional XML configuration files but an alternative option worth considering is spring-boot. It allows you to create completely annotation driven applications that mostly rely on conventions over configuration. Bootstrapping a simple standalone application reduces to:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Main implements CommandLineRunner {

    @Autowired
    private UserService userService;

    public void run(String... args) throws Exception {
        System.out.println(userService.findUser(42L));
    }

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

}


问:
Unit testing when it's harder to come up with concrete cases than write the logic
I have little experience with unit testing, but at the project we're working on right now we decided to do unit testing. The project is a WPF/Entity Framework application, and the part I'm being confused about is a filter function.

Our universe of entities is like this: there are Products, Evaluations and Collections.

Evaluation 1 - n Product

Collection n - m Evaluation

Collection n - m Product

Now the filter function in question is called "in collection", and the logic is like this:
Include the Product if it has a Collection where Collection.Active == true, or if the Product has an Evaluation which in turn has a Collection.

So when unit testing this, I'm trying to find out the different possible corner cases, and make assertions about wether they are included in the filtered list or not. Products which has an active collection, Products which has no active collection but has an evaluation that has a collection, and so on.

The thing is, working out these corner cases is much harder work than writing a simple linq-to-entity query, and it seems that the probability of making an error in the test is much higher than making an error in the implementation of the filter.

How would you handle such situations? It doesn't seem uncommon, especially where there are tools that let you write logic in a simple way. Is it possible to benefit from unit testing here? How?

答:
One strategy I've found that's helped, especially if tests are being added after (potentially long after) the code was developed is to write "component" or "integration" tests first. This isn't to say you should avoid pure unit testing, but if you understand the system's (desired) behavior at a higher level / in a way that seems hard to unit-test, then start by adding tests that gauge correct operation at the level you do understand.

In your case, for instance, build a Collection of Evaluations or a Collection of Products and try some filtering, sifting, sorting or whatever other methods / operations are common to those things.

Yes this will involve multiple classes or modules, and won't be pure unit testing. And yes you should go back and add unit tests to lock down testing at the individual class / module / function level. But starting at the level you do understand gets you going with testing and will help you further discover, reason about, and ultimately add direct unit tests for the more atomic units.


答:
Various reasons

It's pointless and adds complexity - both in the amount of code to write and maintain, and the amount of CPU time needed

It can lose accuracy or worse, corrupt the value entirely

It wastes memory (potentially, depending on language) as you end up storing more representations of a number you need

A good practice is only to keep the first, most accurate representation possible, for any data you receive. Perform any calculations using this data, and only ever convert it if you need to output it or display it in an easier to read format.

Title: Code that converts a value into a different representation, then converts it back to where it started is bad, but how?

Body:
I was reading an article about bad programming practices.

It mentioned -

"Yo-Yo code" that converts a value into a different representation, then converts it back to where it started (eg: converting a decimal into a string and then back into a decimal, or padding a string and then trimming it)

I don't understand why the particular example he gives is a bad way to write programs.  It seems okay to me to convert back if the situation requires it so that the value can be used.

Can anyone explain more about this?


问:
Is it possible to make a printable 'template' document?
I'm writing a piece of software to generate and print nametags. The issue I'm having is that nametags need to be formatted the same, but have different values (ie. different names, titles), and can be on different sizes of paper.

So I need an efficient way to store a sort of 'template' that has certain formatting info (alignment, size and location relative to document's dimensions) and has placeholders for values to be substituted in. Then, at runtime, I need to be able to provide the dimensions of the nametag and the field values, to return a printable document.

My current approach is to have a bunch of pre-written HTML documents which have tables and different sizes, and then substituting the cell values with the given information. The problem with this is that HTML tables are really limited on positioning and sizing of elements. Plus, I end up needing to write javascript to resize and translate elements to handle different sizes of paper and really long field values, which limits code reusability as everyone needs to have the same JS or the files will produce different nametags.

Is there a better way to do this? Is there a printable document type that uses relative sizing and positioning for elements, such that if the values are edited the formatting will be preserved?

I would write my own file type (probably an XML structure) but then anyone using these files would have to use additional code to read my document and turn it into something printable.

答:
Is there a printable document type that uses relative sizing and positioning for elements, such that if the values are edited the formatting will be preserved?

Yes: PostScript. It's a Turing-complete programming language and at the same time a domain-specific language for document layout which can be handled directly by nearly all modern printers.


答:
I don't think there's one right answer because both solutions come with some advantages and disadvantages. I regularly use both depending on the situation.

Having the referenced entity as an object makes this entity class more convenient to use but the downside is that it quickly gets complex to manage all these references. Once the object graph gets more complex you may find yourself in a situation where you can find a chain of references between any two arbitrary entities. Think what happens when you later modify the User class, for example, and add member List<TravelOffer> to it. You now have a cyclic dependency and looking up one entity would require you to follow the graph and lookup a whole bunch of other entities you probably will not need. This all can be managed with proxy classes and lazy loading, for example, but that easily gives you new problems to worry about.

Having the referenced entity as an ID is easy for you to implement but makes the entity class less convenient to use. As you mentioned yourself, it would require you to do extra lookups when you use the entity. Using a singleton does not sound like a good idea so this approach would then limit you to making these lookups only in places where you have access to some kind of a repository that knows how to resolve the IDs.

Title: Should I have an object as attribute or primitive id?

Body:
I am wondering which principle should I use. Here is my situation.

I have a class named TravelOffer. This class looks like this:

```<code>public class TravelOffer
{
    private final long id;

    private final StartZone startZone;
    private final EndZone endZone;
    private final List<Waypoint> waypoints;

    private final Period startOff;

    private final User travelCreator;
    private final List<User> participantsList;

    private final TravelExtras travelExtras;

    private final CandidateApprovement candidateApprovement;

    private int numberOfSeats;

    private double pricePerPerson;

    private Luggage luggage;

    private boolean additionalLuggageTransport;

    private String additionalDescription;
}
</code>```

As u see there are the following attributes:

User tavelCreator and List<User> participantsList

What I am wondering is should it be like this or simply to replace the User object with an String userId and then from a singleton class to get the User object which will be in a Hashmap?


问:
How does hopper prevent disassemble itself?
It's a "how decompiler prevent decompile itself" question.

I have tried :

rename the Mach-O 64-bit executable x86_64 file

remove the LC_UUID and LC_SIGNITURE load commands

but somehow hopper can still identify itself,

saying

You are not allowed to disassemble this program with Hopper.

anyone knows the trick?

答:
Reverse engineering is inherently a tricky business. Even in the best case, with relatively documented products, APIs, or protocols, there will be a lot of details, edge cases, and most of all, original intent that is not stated.

Undocumented systems come next. You have to sit and guess what's going on, try experiments, puzzle over the outcomes, and basically Do Science on the system.

You have the worst case. A system that is actively trying to prevent discovery. The developers of your disassembler clearly understood that "hey, let's try this on itself!" would be some folks' first thought. And the really bad news: There are a lot of different ways to impede discovery. And by dint of them being a disassembler team, they know a good many of them.

So if you're really intent on disassembling this, you will need to either (i) get lucky (e.g. by finding "the answer" on the Internet, which you're already trying), or (ii) be very persistent, tenacious, and disciplined. Reverse engineering is inherently hard, like untangling a tight knot, even in the best case.

Start the easiest way: Use a different disassembler. Competitors aren't likely to care if you disassemble hopper.

Hypothesize defenses and experiment with ways to defeat them. One technique they may be using is hashing various byte sequences within their own executable, then looking for such sequences when they disassemble. You may be able to subvert this by divide and conquer: e.g. by creating copies of the executable that are slices out of the original. You will probably need to know what the proper executable format is and conform your slices to that, so that you're not presenting it an apparently random sequence of bytes, but something that is plausibly an executable. On those pieces you might try varying degrees of fuzzing (i.e. changing random bytes). You will need an automated testing rig for this, because the number of variations you are likely to need to test to get positive results is very large. This would be like decoding the genome by decoding pieces of it at a time.

Do what virus-hunters do. Follow the hopper code execution instruction by instruction from its very first instruction executed. This can be done in a machine code simulator, a step-by-step instruction debugger, or by hand. It's tedious, painstaking, and can require a fair number of tools or a lot of patience. But suss out how the program loads up and establishes its beachhead. This can also be combined with the slicing approach; once you know a snippet of the hopper bootstrap, slice that into a hypothesized short executable and see if hopper recognizes it. If it does, start fuzzing some of the value (either in the executable format/framing, or in the bootstrap sequence).

Work, work, work. Reverse engineering is almost always hard. And here you face intentional impediments and (likely) obfuscation. There's a whole skill set you'll need to develop, much like debugging. Keep pulling those strings, unraveling a little bit at a time. Good luck!

OwnerDisplayName: want


问:
"Everything is a Map", am I doing this right?
I watched Stuart Sierra's talk "Thinking In Data" and took one of the ideas from it as a design principle in this game I'm making. The difference is he's working in Clojure and I'm working in JavaScript.  I see some major differences between our languages in that:

Clojure is idiomatically functional programming

Most state is immutable

I took the idea from the slide "Everything is a Map" (From 11 minutes, 6 seconds to > 29 minutes in).  Some things he says are:

Whenever you see a function that takes 2-3 arguments, you can make a case for turning it into a map and just passing a map in.  There are a lot of advantages to that:

You don't have to worry about argument order

You don't have to worry about any additional information.  If there are extra keys, that's not really our concern.  They just flow through, they don't interfere.

You don't have to define a schema

As opposed to passing in an Object there's no data hiding.  But, he makes the case that data hiding can cause problems and is overrated:

Performance

Ease of implementation

As soon as you communicate over the network or across processes, you have to have both sides agree on the data representation anyway.  That's extra work you can skip if you just work on data.

Most relevant to my question. This is 29 minutes in: "Make your functions composable". Here's the code sample he uses to explain the concept:

```<code>;; Bad
(defn complex-process []
  (let [a (get-component @global-state)
        b (subprocess-one a)
        c (subprocess-two a b)
        d (subprocess-three a b c)]
    (reset! global-state d)))

;; Good
(defn complex-process [state]
  (-> state
    subprocess-one
    subprocess-two
    subprocess-three))
</code>```

I understand the majority of programmers aren't familiar with Clojure, so I'll rewrite this in imperative style:

```<code>;; Good
def complex-process(State state)
  state = subprocess-one(state)
  state = subprocess-two(state)
  state = subprocess-three(state)
  return state
</code>```

Here are the advantages:

Easy to test

Easy to look at those functions in isolation

Easy to comment out one line of this and see what the outcome is by removing a single step

Each subprocess could add more information on to the state.  If subprocess one needs to communicate something to subprocess three, it's as simple as adding a key/value.

No boilerplate to extract the data you need out of the state just so that you can save it back in.  Just pass in the whole state and let the subprocess assign what it needs.

Now, back to my situation:  I took this lesson and applied it to my game.  That is, almost all of my high level functions take and return a gameState object.  This object contains all the data of the game.  EG: A list of badGuys, a list of menus, the loot on the ground, etc.  Here's an example of my update function:

```<code>update(gameState)
  ...
  gameState = handleUnitCollision(gameState)
  ...
  gameState = handleLoot(gameState)
  ...
</code>```

What I'm here to ask about is, have I created some abomination that perverted an idea that is only practical in a functional programming language?  JavaScript isn't idiomatically functional (though it can be written that way) and it's really challenging to write immutable data structures.  One thing that concerns me is he assumes that each of those subprocesses are pure. Why does that assumption need to be made?  It's rare that any of my functions are pure (by that, I mean they often modify the gameState.  I don't have any other complicated side effects other than that).  Do these ideas fall apart if you don't have immutable data?

I'm worried that one day I'll wake up and realize this whole design is a sham and I've really just been implementing the Big Ball Of Mud anti-pattern.

Honestly, I've been working on this code for months and it's been great.  I feel like I'm getting all the advantages he's claimed.  My code is super easy for me to reason about.  But I'm a one man team so I have the curse of knowledge.

Update

I've been coding 6+ months with this pattern. Usually by this time I forget what I've done and that's where "did I write this in a clean way?" comes into play. If I haven't, I'd really struggle. So far, I'm not struggling at all.

I understand how another set of eyes would be necessary to validate its maintainability. All I can say is I care about maintainability first and foremost. I'm always the loudest evangelist for clean code no matter where I work.

I want to reply directly to those that already have a bad personal experience with this way of coding.  I didn't know it then, but I think we're really talking about two different ways of writing code.  The way I've done it appears to be more structured than what others have experienced.  When someone has a bad personal experience with "Everything is a map" they talk about how hard it is to maintain because:

You never know the structure of the map that the function requires

Any function can mutate the input in ways you'd never expect.  You have to look all over the code base to find out how a particular key got into the map or why it disappeared.

For those with such an experience, perhaps the code base was, "Everything takes 1 of N types of maps." Mine is, "Everything takes 1 of 1 type of map". If you know the structure of that 1 type, you know the structure of everything.  Of course, that structure usually grows over time.  That's why...

There's one place to look for the reference implementation (ie: the schema). This reference implementation is code the game uses so it can't get out of date.

As for the second point, I don't add/remove keys to the map outside of the reference implementation, I just mutate what's already there. I also have a large suite of automated tests.

If this architecture eventually collapses under its own weight, I'll add a second update.  Otherwise, assume everything is going well :)

答:
There is more fitting name for what you are doing than Big ball of mud. What you are doing is called the God object pattern. It does not look that way at first sight, but in Javascript there is very little difference between

```<code>update(gameState)
  ...
  gameState = handleUnitCollision(gameState)
  ...
  gameState = handleLoot(gameState)
  ...
</code>```

and

```<code>{
  ...
  handleUnitCollision: function() {
    ...
  },
  ...
  handleLoot: function() {
    ...
  },
  ...
  update: function() {
    ...
    this.handleUnitCollision()
    ...
    this.handleLoot()
    ...
  },
  ...
};
</code>```

Whether or not is it a good idea probably depends on the circumstances. But it is certainly in line with the Clojure way. One of the aims of Clojure is to remove what Rich Hickey calls "incidental complexity". Multiple communicating objects is certainly more complex than a single object. If you split functionality into multiple objects, you suddenly have to worry about communication and coordination and dividing responsibilities. Those are complications that are only incidental to your original goal of writing a program. You should see the Rich Hickey's talk Simple made easy. I think this is a very good idea.

Body:
There is more fitting name for what you are doing than Big ball of mud. What you are doing is called the God object pattern. It does not look that way at first sight, but in Javascript there is very little difference between

update(gameState)
  ...
  gameState = handleUnitCollision(gameState)
  ...
  gameState = handleLoot(gameState)
  ...

and

{
  ...
  handleUnitCollision: function() {
    ...
  },
  ...
  handleLoot: function() {
    ...
  },
  ...
  update: function() {
    ...
    this.handleUnitCollision()
    ...
    this.handleLoot()
    ...
  },
  ...
};

Whether or not is it a good idea probably depends on the circumstances. But it is certainly in line with the Clojure way. One of the aims of Clojure is to remove what Rich Hickey calls "incidental complexity". Multiple communicating objects is certainly more complex than a single object. If you split functionality into multiple objects, you suddenly have to worry about communication and coordination and dividing responsibilities. Those are complications that are only incidental to your original goal of writing a program. You should see the Rich Hickey's talk Simple made easy. I think this is a very good idea.


问:
Explicitly define enum values, even if the default value is the same?
There are times when an enum's values are important: it is not necessary for them to be unique, they also need to have specific values. In such cases, should the values be explicitly defined, even if they coincide with the defaults? An example:

```<code>enum Car {
    DeLorean = 0,
    Lada = 1
};
</code>```

Imagine that for whatever reason your application assumes that DeLorean and Lada have those specific values. Incidentally, they are the same as the default values but does that mean it is no longer necessary to use explicit definitions?

Leaving them implicit makes me uneasy. It seams to me that having them explicitly defined is communicating to future programmers that the specific values are important and it helps prevent mistakes like this:

```<code>enum Car {
    Dacia,
    DeLorean,
    Lada
};
</code>```

In the example above, another programmer who is not aware of the restriction I mentioned introduces a new enum value and, wanting to keep the code tidy, puts it in alphabetical order. However, DeLorean and Lada now have different numerical values and a potentially silent bug has been introduced.

My reasoning seems correct to me (obviously), but the code review team for a company I used to work with didn't agree. Am I wrong?

答:
This is very much a judgement call, but I would agree with you that explicit values are the way to go, plus a comment at the start explaining the significance of the explicit values.

As an example of a prominent project that is doing it this way, look at Clang's AST serialization. It uses a huge enum to define codes for all of its AST nodes, and the enum has explicit values.

That said, I also sympathize with the opinion of the architecture team that touching old code that works when there's more important things to be done is not the best idea.

I don't like the compromise solution, though. It adds nothing.


答: Consider C++11's enum class; it allows you and your company to eliminate the need for explicit values while removing the subtle bugs enum has.

Title: Explicitly define enum values, even if the default value is the same?

Body:
There are times when an enum's values are important: it is not necessary for them to be unique, they also need to have specific values. In such cases, should the values be explicitly defined, even if they coincide with the defaults? An example:

```<code>enum Car {
    DeLorean = 0,
    Lada = 1
};
</code>```

Imagine that for whatever reason your application assumes that DeLorean and Lada have those specific values. Incidentally, they are the same as the default values but does that mean it is no longer necessary to use explicit definitions?

Leaving them implicit makes me uneasy. It seams to me that having them explicitly defined is communicating to future programmers that the specific values are important and it helps prevent mistakes like this:

```<code>enum Car {
    Dacia,
    DeLorean,
    Lada
};
</code>```

In the example above, another programmer who is not aware of the restriction I mentioned introduces a new enum value and, wanting to keep the code tidy, puts it in alphabetical order. However, DeLorean and Lada now have different numerical values and a potentially silent bug has been introduced.

My reasoning seems correct to me (obviously), but the code review team for a company I used to work with didn't agree. Am I wrong?


问:
What is the point behind building an abstraction layer PDO Adapter class instead of using native PDO?
I have built a PDO adapter class because I thought, at the time anyway, it would be a good idea.  After fighting with it, it makes no sense to me.  Isn't the design of PDO the way it is to keep you from having to create special adapters for a given database?

For a connection, I understand, but I seem to be replacing PDO with my own version of PDO.

I do not understand why I would need this extra layer of abstraction.

Here are some examples:

```<code>public function prepare($sql, array $options = array()) {
    $this->connect();
    try {
        $this->statement = $this->connection->prepare($sql,
            $options);
        return $this;
    }
    catch (PDOException $e) {
        throw new RunTimeException($e->getMessage());
    }
}

public function execute(array $parameters = array()) {
    try {
        $this->getStatement()->execute($parameters);
        return $this;
    }
    catch (PDOException $e) {
        throw new RunTimeException($e->getMessage());
    }
}

public function countAffectedRows() {
    try {
        return $this->getStatement()->rowCount();
    }
    catch (PDOException $e) {
        throw new RunTimeException($e->getMessage());
    }
}

public function getLastInsertId($name = null) {
    $this->connect();
    return $this->connection->lastInsertId($name);
}
</code>```

EDIT: I found this.  I think I may be in overkill.  I could possibly have this class for other things, but not native PDO without a more compelling reason.

https://stackoverflow.com/questions/20664450/is-a-pdo-wrapper-really-overkill

答:
Indeed, you could have been using PDO directly. The only real thing it does is to rethrow PDOException as RunTimeException, a practice which should be avoided at all costs.

This being said, PDO doesn't keep you from having to create special adapters for a given database, since different databases have different syntax and functionality which cannot possibly be handled by PDO. It works for simple stuff like PDOStatement::rowCount(), but PDO won't help you if, for example, you need to LIMIT/OFFSET the number of results in MySQL and Microsoft SQL, forcing you to write LIMIT/OFFSET query for one and WHERE rowNumber BETWEEN ... AND ... for another.

Moreover, the presence of PDO doesn't mean you shouldn't have a database layer either: your business layer shouldn't call PDO directly.

Example

If a website needs to display the number of users, business layer will call database layer IDatabase similarly to this:

```<code>$countUsers = $this->data->countAllUsers();
</code>```

Then, you'll have an implementation for Microsoft SQL Server:

```<code>class SqlServerDatabase implements IDatabase
{
    ...
    public function countAllUsers()
    {
        $query = 'select count(1) from [Community].[User]';
        $statement = $this->connection->prepare($query);
        $statement->execute();
        return $statement->fetchColumn();
    }
    ...
}
</code>```

and another one for MySQL:

```<code>class SqlServerDatabase implements IDatabase
{
    ...
    public function countAllUsers()
    {
        $query = 'select count(*) from `user`';
        $statement = $this->connection->prepare($query);
        $statement->execute();
        return $statement->fetchColumn();
    }
    ...
}
</code>```

If you have a lot of table-counting, you may want to refactor that to reduce code duplication. Without PDO, you won't be able to do that. With PDO, you can:

```<code>abstract class DatabaseCommon
{
    protected function countAllRows(TableName $tableName, $preferOneToAsterisk = false)
    {
        $query = $preferOneToAsterisk ?
            'select count(1) from ' . $tableName->sanitize() :
            'select count(*) from ' . $tableName->sanitize();

        $statement = $this->connection->prepare($query);
        $statement->execute();
        return $statement->fetchColumn();
    }
}

class SqlServerDatabase extends DatabaseCommon implements IDatabase
{
    public function countAllUsers()
    {
        return $this->countAllRows(
            new MicrosoftSqlTableName('Community', 'User'),
            true
        );
    }
}

class SqlServerDatabase extends DatabaseCommon implements IDatabase
{
    public function countAllUsers()
    {
        return $this->countAllRows(new MySqlTableName('user'));
    }
}
</code>```

Body:
Indeed, you could have been using PDO directly. The only real thing it does is to rethrow PDOException as RunTimeException, a practice which should be avoided at all costs.

This being said, PDO doesn't keep you from having to create special adapters for a given database, since different databases have different syntax and functionality which cannot possibly be handled by PDO. It works for simple stuff like PDOStatement::rowCount(), but PDO won't help you if, for example, you need to LIMIT/OFFSET the number of results in MySQL and Microsoft SQL, forcing you to write LIMIT/OFFSET query for one and WHERE rowNumber BETWEEN ... AND ... for another.

Moreover, the presence of PDO doesn't mean you shouldn't have a database layer either: your business layer shouldn't call PDO directly.

Example

If a website needs to display the number of users, business layer will call database layer IDatabase similarly to this:

$countUsers = $this->data->countAllUsers();

Then, you'll have an implementation for Microsoft SQL Server:

class SqlServerDatabase implements IDatabase
{
    ...
    public function countAllUsers()
    {
        $query = 'select count(1) from [Community].[User]';
        $statement = $this->connection->prepare($query);
        $statement->execute();
        return $statement->fetchColumn();
    }
    ...
}

and another one for MySQL:

class SqlServerDatabase implements IDatabase
{
    ...
    public function countAllUsers()
    {
        $query = 'select count(*) from `user`';
        $statement = $this->connection->prepare($query);
        $statement->execute();
        return $statement->fetchColumn();
    }
    ...
}

If you have a lot of table-counting, you may want to refactor that to reduce code duplication. Without PDO, you won't be able to do that. With PDO, you can:

abstract class DatabaseCommon
{
    protected function countAllRows(TableName $tableName, $preferOneToAsterisk = false)
    {
        $query = $preferOneToAsterisk ?
            'select count(1) from ' . $tableName->sanitize() :
            'select count(*) from ' . $tableName->sanitize();

        $statement = $this->connection->prepare($query);
        $statement->execute();
        return $statement->fetchColumn();
    }
}

class SqlServerDatabase extends DatabaseCommon implements IDatabase
{
    public function countAllUsers()
    {
        return $this->countAllRows(
            new MicrosoftSqlTableName('Community', 'User'),
            true
        );
    }
}

class SqlServerDatabase extends DatabaseCommon implements IDatabase
{
    public function countAllUsers()
    {
        return $this->countAllRows(new MySqlTableName('user'));
    }
}


答:
I would rephrase the description as "code which converts a type to a different representation for the purpose of doing something which could have been done just as well or better in the original and then converts it back.  There are many situations where converting something to a different type, acting upon it, and converting it back is entirely appropriate and failure to do so would result in incorrect behavior.

As an example where conversion is good:

One has four float values of arbitrary signs whose magnitudes may differ by a factor of up to 1,000, and one needs to compute the sum to within 0.625 units in the last place.  Converting all four values to double, computing the sum, and converting the result back to float will be much more efficient than would be any approach using float alone.

 Floating-point values are at best accurate to 0.5 units in the last place (ULP).   This example would require that the worst-case rounding error by no more than 25% above optimum worst-case error.  Using a double will yield a value which will be accurate within 0.5001 ULP. While a 0.625 ULP requirement might seem contrived, such requirements are often important in successive-approximation algorithms. The more tightly the error bound is specified, the lower the worst-case iteration requirement.

As an example where conversion is bad:

One has a floating-point number, and wishes to output a string which will represent its value uniquely.  One approach is to convert the number to a string with a certain number of digits, try to convert it back, and see if the result matches.

But this is actually a poor approach.  If a decimal string represents a value which sits almost precisely on the halfway point between two floating-point values, it's fairly expensive for a string-to-float method to guarantee that it will always yield the nearer float value, and many such conversion methods don't uphold such a guarantee (among other things, doing so would in some cases require reading all the digits of a number, even if it was billions of digits long).

It is much cheaper for a method to guarantee that it will always return a value that is within 0.5625 units in the last place (ULP) of the represented value.  A robust "reversible" decimal-to-string formatting routine should compute how far the output value is from the correct value, and continue outputting digits until the result is within 0.375 (ULP) if not 0.25 (ULP).  Otherwise, it may output a string which some conversion methods will process correctly, but other conversion methods won't.

It is better to sometimes output a digit that might not be "necessary" than output a value that might be misinterpreted.  The key part is that the decision of how many digits should be output should be made based upon numeric calculations related to the output process, rather than upon the result of one particular method's attempt to convert the string back to a number.


答:
I've tried a few things in this area, all with limited but acceptable success.

HTML + CSS. With proper formatting (no px, always em, CSS paged media rules, etc) you can achieve nice-enough results. You need to be sure you have proper fonts installed at the printing site, and most likely you'll have various headers / footers added by the browser on the page. You won't get pixel-perfect results, at least not in a stable way. OTOH you'll get your page nicely adapt to various text lengths, you can inject reasonable formatting tags if your text is not always plain, etc.

OpenOffice template documents. Lay out a document, define named fields, define a macro to replace them, then run it programmatically. OOo does run in a headless mode (-headless), so you'll get a sort of 'template-processing and printing server'. Beats other solutions when you need user-editable templates and when you need to export MS Word .doc files. Not a piece of cake to set up, though. E.g. if you print a lot, you'll need to manage a queue for parallel requests yourself.

PostScript. Only works if you have a postscript printer (most consumer-grade cheap printers don't support it), or are willing to use ghostscript for printing. I created a bare-bones document, saved ('printed') it as PostScript, then edited to taste, to allow simple text substitution. Works great when you have a lot of line graphics, like legal forms, and want pixel-perfect printouts, but you don't get any automatic layout: if a text string does not fit in a box, it will protrude outside. (You can handle this in PS, but making this reliably is often painful, for you'll need to move more page elements than you think.)

Choose your poison.

I'd not look at PDF: what you get is basically all the limitations of the Postscript approach with none of its (relative) transparency and malleability. You can easily transform PS to PDF using ghostscript, though.

Title: Is it possible to make a printable 'template' document?

Body:
I'm writing a piece of software to generate and print nametags. The issue I'm having is that nametags need to be formatted the same, but have different values (ie. different names, titles), and can be on different sizes of paper.

So I need an efficient way to store a sort of 'template' that has certain formatting info (alignment, size and location relative to document's dimensions) and has placeholders for values to be substituted in. Then, at runtime, I need to be able to provide the dimensions of the nametag and the field values, to return a printable document.

My current approach is to have a bunch of pre-written HTML documents which have tables and different sizes, and then substituting the cell values with the given information. The problem with this is that HTML tables are really limited on positioning and sizing of elements. Plus, I end up needing to write javascript to resize and translate elements to handle different sizes of paper and really long field values, which limits code reusability as everyone needs to have the same JS or the files will produce different nametags.

Is there a better way to do this? Is there a printable document type that uses relative sizing and positioning for elements, such that if the values are edited the formatting will be preserved?

I would write my own file type (probably an XML structure) but then anyone using these files would have to use additional code to read my document and turn it into something printable.


问:
Should I couple these classes?
I am programming in Python. I have several complicated/hard-to-understand XML files that describe the structure of an election. I am trying to write a python wrapper that makes it easy to access this data.

The structure of the entities I am trying to model is: there is an election. Elections have races. Races consist of candidates who get results in precincts. Precincts are organized into counties.

I first built this so that the election class holds an array of races objects which hold arrays of candidate objects and result objects. But now  I am starting to write unit tests and it is hard to test the candidates or races (because they are coupled to the election).

The election has information about the races, which it feeds to each race's constructor. The race has information about the candidates (i.e. what they are running for), which it feeds to their constructors.

I know that it is in general a good idea to have decoupled classes but in this case there is a natural hierarchy in the domain and I am wondering to what extent it makes sense to have my code reflect this hierarchy. The ultimate goal of this is to write out "results" in json (for a web app) that are  much, much easier to parse than the XML. The results will change every few minutes as they come in (on a new election xml file). I'd love some design advice.

答:
Premise 1: Many applications are strictly Data Processing in the 1960s definition. The Swiss Army Knife of Data Processing is the Relational Database model.

Lemma 1: Third Normal Form is an efficient way of representing data.

A Precinct has-a County, but no other relation cares about that. Make a mapping (dict) between Precinct and County which is unrelated to any other bindings.

The Election needs to have a collection of Races but it doesn't need any other information.

A Race needs (Candidate, Office, Party?) but that is decoupled from the Vote.

A Vote needs (Race, Candidate, Precinct) but no more.

I decoupled the data classes, oh noes! However, I did normalize the data which makes composition into well-structure data much easier to think about, which will yield more sensible JSON. Unless you are voting for hoopiest frood, you'll probably want to store this stuff in a database, and it is already in the proper form for doing that.

The design as you described it relies on a god-object, Election, and that's rarely a good idea. If you find a class constructor needs a bunch of data to pass to a bunch of other constructors, you are on your way to a god-object. You'll gain more flexibility and easier unit-testing by decoupling pieces of implementation.

Moral: Don't ignore traditional approaches when faced with a traditional problem.

Title: Should I couple these classes?


问:
What should my RESTful API method look like for a Roulette game?
I'm building a roulette game for fun, and the game will use a RESTful API. I'm building out the functionality for spinning the roulette wheel.

I'm using MongoDB and have a collection for players

```<code>_id
username
balance
games
    _id
    game_name
    last_bet_at
    created_at
last_logged_in_at
created_at
</code>```

and another collection, player_game_logs, for all plays that happen in games

```<code>_id
player_game_id
game_name
bets (object)
result (object)
win_amount
loss_amount
balance
ip_address
created_at
</code>```

I'm not sure what the RESTful API method should look like for telling the server to spin the roulette wheel and record a player game log for the play. Obviously I need to POST against a resource, and I'm not sure what that resource should be. Perhaps I even need an additional MongoDB collection.

Here are two possible methods I've come up with...

Method 1

```<code>POST /games/roulette/spin

request
{
    bets: {
        even: 1,
        red: 1
    }
}

response
{
    balance: 156,
    result: {
        "color": "black",
        "number": "31"
    },
    win_amount: 0,
    lose_bets: {
        even: 1,
        red: 1
    }
}
</code>```

Method 2

```<code>POST /players/game_logs

request
{
    player_game_id: 1234,
    game_name: 'roulette',
    bets: {
        even: 1,
        red: 1
    }
}

response
{
    player_game_id: 1234,
    game_name: 'roulette',
    result: {
        color: 'black',
        number: 10
    },
    win_amount: 0,
    loss_amount: 2,
    balance: 156
}
</code>```

I favor method 2. Is there anything wrong with this method, and what might be a better approach?

答: Method 2: Game logs doesn't sound to be good API name. Try and give better name for URI's. You can use some of of REST features in urls. For example you can use urls like POST /players/game/{game_id}. URL's can be more specific to the resource.</p>


问:
Filesystem superblocks and their backup copies
I'd like to understand how (modern) filesystems are implemented and having trouble to fully understand superblocks and their backups. I reference ext4 and btrfs, but the questions may also apply to other filesystems.

Ext4 stores a couple of superblocks (my fs for example has one primary and seven backup SBs). I do understand that, since the superblock defines important characteristics of the filesystem, an inline backup makes sense. But I don't get why so many backups, so:

Why store so many superblocks? What's the benefit of having 7 backup SBs versus e.g just one?

According to ext4 documentation ext4 stores a "write time" within the SB (last write since epoch). That would imply that every write-transaction also consists of a write to the SB. Given my system, having 7 backup SBs, each write-transaction would consist of 8 SB writes. That seems a ridiculous amount of non-sequential metadata writes for a single transaction, leading to the question:

Am I correct that on ext4 SBs are written that often?

The same questions basically apply to btrfs where SBs are distributed among static address blocks (primary block at 0x10000) and only in SSD mode (due to wear leveling concerns) only one is written per commit.

Is there a benefit for btrfs to store the primary superblock at 0x10000 instead of 0x0?

The documentation of btrfs also states:
Note that btrfs only recognizes disks with a valid 0x10000 superblock; otherwise, there would be confusion with other filesystems. This is even more confusing since a broken SB at 0x10000 would lead to an invalid filesystem, even if there're other valid SBs at other locations.

How does btrfs benefit from superblock backups, if the filesystem is invalid on a broken primary superblock?

答:
This is diving a little deep into the specific underlying structures of filesystems, which are very complicated and idiosyncratic. But here goes...

First, superblocks are not one thing. They differ, filesystem to filesystem, in what information they contain. The two filesystems you mention, extN and btrfs, are much evolved and not all that similar to grandpa Unixes. And most of the grandpa Unixes like AIX, HP-UX, IRIX, and Solaris are at least some distance removed from the BSD "Fast File System" and original Nth Edition Unix file systems.

But in all of the implementations I've seen, the different variations on superblocks may sit at the top of the filesystem metadata hierarchy, but they are not the primary metadata blocks for the file system, nor the data structure that is most often updated. They are not updated every write, for example, nor even every metadata update or directory modification. The reason they are so multiply-replcated / well-protected is that, sitting at the top of the file system structure, they define the filesystem parameters (some of which are semantically critical to proper operation), and knit together all of the the other metadata structures. Without them, even finding all of the other metadata structures would be difficult, much less getting a perfect, as-originally-intended interoperation of them.

Over the years, the ability of filesystem check-and-repair tools (fsck is the great grandpappy of them all) to repair from catastrophic failures (like "superblock loss") has improved. But it's ugly, slow, and heuristic (i.e. potentially imperfect = possible data loss) on almost all of them. And the things all Unix implementations have striven for over the years include higher reliability, more robust storage, and faster boot times). Having a plodding check-and-repair process is an impediment to all. Thus the move to N-way replication.

Because superblocks (or more generally, all of the blocks/data structures defining the filesystem as a whole) are not the most active ("hottest") metadata in the system (only the highest level), and because their loss is so damaging, designers conclude we can afford 2- or more-way replication. They tend to have their data flushed to disk only periodically (e.g. every 30 seconds). Thus their performance/update overhead is minimal.

I haven't used btrfs or tried to recover it from failure, so I have no particular insight into its peculiar restrictions on superblock placement, or what special load-leveling constraints are typically enabled for SSD operation. But like other filesystem designs, its management tool (btrfsck) has a specific option (-u) to manually specify the use of a secondary or tertiary superblock. In extfs, the corresponding option is -b. Every other Unix filesystem has similarly idiosyncratic controls/commands for repair procedures in its corresponding tool.


问:
How to diversify an optimal solution set?
If given a list of players, their salaries, and their projections, one can easily find the top 'n' projected teams (where a team is a combination of players), such that every team is under the salary cap. Yet, these teams will share very similar rosters. Is there an algorithm that will diversify the solution set, while preserving some sort of 'optimality'? How do mutual funds, wanting to maximize an investment vehicle's expected return, generate diverse indexes and funds? </p>

答: Effectively you're in a situation similar to a chess engine. You want to find as many possible states within a certain number of moves from a given checkmate state. In chess, solving all of these would be impractical to the point of absurdity but for small state systems, this would be possible. You figure out a given optimal solution for a set of players and so forth. Then you do single permutations on players and then expand the number of players permuted until you've got a solution set that is sufficiently diverse. Thus you can cap the search space to something manageable whilst still maintaining some level of optimization and diversity.</p>


答:
In new code, if it is part of the system or business requirements that a particular enumeration be equal to a specific value then it should definitely be explicit, commented and documented. Failure to do so invites a maintenance nightmare.

The only factor in your scenario that would delay me from making such enums explicit is the fact that this is old code from a working code base and other tasks might have priority.


问:
Is it a good practice to run unit tests in version control hooks?
From the technical point of view it is possible to add some pre/post push hooks which will run unit tests before allowing some specific commit to be merged to remote default branch.

My question is - is it better to keep unit tests in build pipeline (thus, introducing broken commits to repo) or it's better just not to allow "bad" commits to happen.

I do realize that I'm not limited with this two options. For instance, I can allow all commits to branched and tests before pushing merge commit to repo. But if you have to choose between exactly this two solutions, which one you'll choose and for what exactly reasons?

答:
No, it's not, for two reasons:

Speed

Commits should be fast. A commit which takes 500 ms., for example, is too slow and will encourage developers to commit more sparingly. Given that on any project larger than a Hello World, you'll have dozens or hundreds of tests, it will take too much time to run them during pre-commit.

Of course, things get worse for larger projects with thousands of tests which run for minutes on a distributed architecture, or weeks or months on a single machine.

The worst part is that there is not much you can do to make it faster. Small Python projects which have, say, hundred unit tests, take at least a second to run on an average server, but often much longer. For a C# application, it will average four-five seconds, because of the compile time.

From that point, you can either pay extra $10 000 for a better server which will reduce the time, but not by much, or run tests on multiple servers, which will only slow things down.

Both pay well when you have thousands of tests (as well as functional, system and integration tests), allowing to run them in a matter of minutes instead of weeks, but this won't help you for small scale projects.

What you can do, instead, is to:

Encourage developers to run tests strongly related to the code they modified locally before doing a commit. They possibly can't run thousands of unit tests, but they can run five-ten of them.

Make sure that finding relevant tests and running them is actually easy (and fast). Visual Studio, for example, is able to detect which tests may be affected by changes done since the last run. Other IDEs/platforms/languages/frameworks may have similar functionality.

Keep the commit as fast as possible. Enforcing style rules is OK, because often, it's the only place to do it, and because such checks are often amazingly fast. Doing static analysis is OK as soon as it stays fast, which is rarely the case. Running unit tests is not OK.

Run unit tests on your Continuous Integration server.

Make sure developers are informed automatically when they broke the build (or when unit tests failed, which is practically the same thing if you consider a compiler as a tool which checks some of the possible mistakes you can introduce into your code).

For example, going to a web page to check the last builds is not a solution. They should be informed automatically. Showing a popup or sending an SMS are two examples of how they may be informed.

Make sure developers understand that breaking the build (or failing regression tests) is not OK, and that as soon as it happens, their top priority is to fix it. It doesn't matter whether they are working on a high-priority feature that their boss asked to ship for tomorrow: they failed the build, they should fix it.

Security

The server which hosts the repository shouldn't run custom code, such as unit tests, especially for security reasons. Those reasons were already explained in CI runner on same server of GitLab?

If, on the other hand, your idea is to launch a process on the build server from the pre-commit hook, then it will slow down even more the commits.


答:
Commits should run fast.  When I commit some code I want it to get pushed to the server.  I don't want to wait a few minutes while it runs a battery of tests.  I am responsible for what I push to the server and don't need anyone babysitting me with commit hooks.

That said, once it gets to the server, it should be analyzed, unit tested, and built immediately (or within a short time frame).  This would alert me to the fact that unit tests are broken, or it didn't compile, or I made a mess shown by the static analysis tools available.  The faster this is done (the build and analysis), the faster my feedback and the faster I am able to fix it (the thoughts haven't completely swapped out of my brain).

So no, don't put tests and such in commit hooks on the client.  If you must, put them on the server in a post commit (because you don't have a CI server) or on the CI build server and alert me appropriately to issues with the code.  But do not block the commit from happening in the first place.

I should also point out that with some interpretations of Test Driven Development, one should check in a unit test that breaks first.  This demonstrates and documents the bug is present.  Then a later checkin would be the code that fixes the unit test.  Preventing any checkins until the unit tests pass would reduce the effective value of checking in a unit test that fails to document the issue.

Related: Should I have unit tests for known defects? and What is the value of checking in failing unit tests?

Title: Is it a good practice to run unit tests in version control hooks?

Body:
From the technical point of view it is possible to add some pre/post push hooks which will run unit tests before allowing some specific commit to be merged to remote default branch.

My question is - is it better to keep unit tests in build pipeline (thus, introducing broken commits to repo) or it's better just not to allow "bad" commits to happen.

I do realize that I'm not limited with this two options. For instance, I can allow all commits to branched and tests before pushing merge commit to repo. But if you have to choose between exactly this two solutions, which one you'll choose and for what exactly reasons?


问:
negative boolean expressions and eager boolean OR
I come across these kinds of expressions and I have hard time reading it.
How do you read it properly to see if it is the right logic when debugging.</p>

```<code>if (!(userLoggedIn || isAdmin)) {
    console.log('User does not have rights');
    }
</code>```

答:
Firstly expand the shorthand

```<code>if (! (userLoggedIn = true  || isAdmin = true ))
</code>```

Then replace logical operators with words

```<code>if (not (userLoggedIn = true or isAdmin= true))
</code>```

Then translate

```<code>If the user is not either logged in or admin
{
    //do something
}
</code>```

Once you've thought about it like this the first time, the original becomes pretty trivial to read in one go - suddenly it clearly states 'if the user is not either logged in or admin' without any need to translate, this is also the beauty of good Boolean variable names as seen in this example

```<code>if (!(userLoggedIn || isAdmin))
</code>```

Body:
Firstly expand the shorthand

if (! (userLoggedIn = true  || isAdmin = true ))

Then replace logical operators with words

if (not (userLoggedIn = true or isAdmin= true))

Then translate

If the user is not either logged in or admin
{
    //do something
}

Once you've thought about it like this the first time, the original becomes pretty trivial to read in one go - suddenly it clearly states 'if the user is not either logged in or admin' without any need to translate, this is also the beauty of good Boolean variable names as seen in this example

if (!(userLoggedIn || isAdmin))


问:
Is staying implementation agnostic really worth it?
I have a project that I'm working on currently using Tomcat, Spring 4, Spring Security, MySQL, and JPA w/ Hibernate.

I picked JPA from the standpoint that it's suppose to make swapping out the underlying implementation of ORM providers seamless, or at least less painful. I would say that this is  mentally using the spec over the implementation (JAX-RS) is the default standpoint of the Java development community.

I'm curious if this is really a task worth doing. I'm sure if I used Hibernate directly I would gain some power because I could use features that are not part of the main JPA specification.

Part of my concern comes from the idea of YAGNI. I'm essentially programming in a specific style and fashion (using JPA instead of Hibernate) so that at some point in the future I can swap out my ORM implementation. I severely doubt that will ever happen over the life of the product, so I'm essentially putting effort into something that I'll probably never reap the benefits of.

What are your thoughts? Is "programming to the interface" worth it when it comes to stuff like JPA? Have you ever actually swapped an entire ORM implementation in a product? Have you ever been able to completely avoid the abstraction from something like JPA leaking anyways? I personally have a single native SQL call already (to clean out the database tables), and there's somethings I'd like to futz with that are built into the JPA spec (get/set prefixes to your methods, and the difference between MEMBER OF/IN, which only binding myself to an underlying implementation will get me any chance of avoiding.

答:
The problem with implementation agnosticism is that you will, in your time as a developer, waste time either way.

I've written several projects which we wasted a load of time writing to an interface, which were then never used in any new way, never converted and just used 'as is' for years

I've also wasted a load of time converting software that nobody ever expected to need to be converted.

The only real observation I have to make, is that the former is a lot less painful.


问:
Manage ClickOnce releases for different parties
I'm struggling with release management of a piece of software. First some general information:

It is a ClickOnce application

I follow the release often practice

There are about 30 parties served with this software

I need full control which update will be delivered to which party

Not each party is allowed to get the latest update/release

Each party has multiple clients that are all allowed to get the latest update, served for the specific party

So that's what my requirements are in a rough description. So let me explain what I was thinking about how to solve this.

I would like to create a "deployment" website (asp.net) that will handle all the requests

There are two endpoints one for download the client and one where the client checks for updates

So each party has a separate endpoint like DeploymentSite/party1 and another for DeploymentSite/party2

The Application Files should still be stored centralized

So I thought it would be manageable with mage.exe with the following steps

Build application and store new release into Application Files Repository/Folder

Get parties that should be updated (config file, database what ever)

Run mage.exe to create a new application and deployment manifest for each party in the update list with new Application File Location (1.0.2)

Actually I'm really struggling with this mage.exe staff. I can't create the appropriate files with the needed codebase.

How to handle thes requirements?

答: I have a similar situation and my plan is to use Octopus deploy and slowcheetah for app.config transforms to create a package which then has multiple deployment targets for each unique customer.</p>


问:
What can one do to improve readability of math-oriented code in C#, Java, and similar?
As both a C programmer and a C# programmer, one of the things I don't like about C# is how verbose math functions are. Every time you would have to use a Sin, cosine, or power function for example, you'd have to prepend the Math static class. This leads to very long code when the equation itself is pretty simple. The problem becomes even worse if you need to typecast data types. As a result, in my opinion, the readability suffers. For example:

```<code>double x =  -Math.Cos(X) * Math.Sin(Z) + Math.Sin(X) * Math.Sin(Y) * Math.Cos(Z);
</code>```

As opposed to simply

```<code>double x = -cos(X) * sin(Z) + sin(X) * sin(Y) * cos(Z);
</code>```

This is also the case in other langauges like Java.

I'm not sure if this question actually has a solution, but I would like to know if there are any tricks C# or Java programmers use to improve readability of Math code. I realize however that C#/Java/etc. are not math-oriented languages like MATLAB or similar, so it makes sense. But occasionally one would still need to write math code and it'll be great if one could make it more readable.

答:
You could define local functions that call the global static functions. Hopefully the compiler will inline the wrappers, and then the JIT compiler will produce tight assembly code for the actual operations. For example:

```<code>class MathHeavy
{
    private double sin(double x) { return Math.sin(x); }
    private double cos(double x) { return Math.cos(x); }

    public double foo(double x, double y)
    {
        return sin(x) * cos(y) - cos(x) * sin(y);
    }
}
</code>```

You could also create functions that bundle up common math operations into single operations. This would minimize the number of instances where functions like sin and cos appear in your code, thereby making the clunkiness of invoking the global static functions less noticeable. For example:

```<code>public Point2D rotate2D(double angle, Point2D p)
{
    double x = p.x * Math.cos(angle) - p.y * Math.sin(angle);
    double y = p.x * Math.sin(angle) + p.y * Math.cos(angle);

    return new Point2D(x, y)
}
</code>```

You are working at the level of points and rotations, and the underlying trig functions are buried.

Body:
You could define local functions that call the global static functions. Hopefully the compiler will inline the wrappers, and then the JIT compiler will produce tight assembly code for the actual operations. For example:

class MathHeavy
{
    private double sin(double x) { return Math.sin(x); }
    private double cos(double x) { return Math.cos(x); }

    public double foo(double x, double y)
    {
        return sin(x) * cos(y) - cos(x) * sin(y);
    }
}

You could also create functions that bundle up common math operations into single operations. This would minimize the number of instances where functions like sin and cos appear in your code, thereby making the clunkiness of invoking the global static functions less noticeable. For example:

public Point2D rotate2D(double angle, Point2D p)
{
    double x = p.x * Math.cos(angle) - p.y * Math.sin(angle);
    double y = p.x * Math.sin(angle) + p.y * Math.cos(angle);

    return new Point2D(x, y)
}

You are working at the level of points and rotations, and the underlying trig functions are buried.


答:
Within Java, there are many tools available to make certain things less verbose, you just have to be aware of them.  One that is useful in this case is that of the static import (tutorial page, wikipedia).

In this case,

```<code>import static java.lang.Math.*;

class Demo {
    public static void main (String[] args) {
        double X = 42.0;
        double Y = 4.0;
        double Z = PI;

        double x =  -cos(X) * sin(Z) + sin(X) * sin(Y) * cos(Z);
        System.out.println(x);
    }
}
</code>```

runs quite nicely (ideone).  It's a bit heavy handed to do a static import of all of the Math class, but if you are doing a lot of math, then it might be called for.

The static import allows you to import a static field or method into the namespace of this class and invoke it without requiring the package name.  You often find this in Junit test cases where import static org.junit.Assert.*; is found to get all the asserts available.

Title: What can one do to improve readability of math-oriented code in C#, Java, and similar?

Body:
As both a C programmer and a C# programmer, one of the things I don't like about C# is how verbose math functions are. Every time you would have to use a Sin, cosine, or power function for example, you'd have to prepend the Math static class. This leads to very long code when the equation itself is pretty simple. The problem becomes even worse if you need to typecast data types. As a result, in my opinion, the readability suffers. For example:

```<code>double x =  -Math.Cos(X) * Math.Sin(Z) + Math.Sin(X) * Math.Sin(Y) * Math.Cos(Z);
</code>```

As opposed to simply

```<code>double x = -cos(X) * sin(Z) + sin(X) * sin(Y) * cos(Z);
</code>```

This is also the case in other langauges like Java.

I'm not sure if this question actually has a solution, but I would like to know if there are any tricks C# or Java programmers use to improve readability of Math code. I realize however that C#/Java/etc. are not math-oriented languages like MATLAB or similar, so it makes sense. But occasionally one would still need to write math code and it'll be great if one could make it more readable.

Body:
Within Java, there are many tools available to make certain things less verbose, you just have to be aware of them.  One that is useful in this case is that of the static import (tutorial page, wikipedia).

In this case,

import static java.lang.Math.*;

class Demo {
    public static void main (String[] args) {
        double X = 42.0;
        double Y = 4.0;
        double Z = PI;

        double x =  -cos(X) * sin(Z) + sin(X) * sin(Y) * cos(Z);
        System.out.println(x);
    }
}

runs quite nicely (ideone).  It's a bit heavy handed to do a static import of all of the Math class, but if you are doing a lot of math, then it might be called for.

The static import allows you to import a static field or method into the namespace of this class and invoke it without requiring the package name.  You often find this in Junit test cases where import static org.junit.Assert.*; is found to get all the asserts available.


问:
How to write tasks in Jira when using Scrum?
I am going to start a new project using Scrum and Jira and I have some questions regarding how to write proper tasks in Jira.

From what I understand user stories are small non-technical descriptions written by the stakeholders (ideally) that can have the form: As a user I want to order monkies so I can earn money.

However these tasks must be elaborated with requirements, technical requirements etc. My question is: How do you write such tasks in Jira properly, and do I have the right understanding of user stories.

Should I create user stories as super tasks and then create subtasks with the actual tasks/requirements?

Should I estimate super tasks/user stories, or only the sub tasks?

答:
Using hierarchy like Epic -> Story/Task -> SubTask works great with few exceptions:

There is no way in JIRA to plan which SubTask the team committed to finish in the single Sprint

If the Story/Task is BIG then 1 level of decomposition could be not enough

In this way both Story and Task serve the same purpose and are interchangeable.

We go with a deeper hierarchy: Epic -> Story -> Task -> Task -> ...

Here Story is short for User Story, capturing requirements and own by Product.
Task on another hand is the result of decomposition of the Story or another big Task and own by Development.

The only problem in this case is that naturally GH doesn't offer a way to define relationship between Story and Tasks. We are using Parent -- Child link, it needs to be maintained manually.

I saw a 3rd party plug-in defining hierarchical relationship between issues and reporting on consolidated Children to Parent estimates and spent time. I didn't use it, so won't mention it here for now.


答:
In addition to the other good answers here, I might also recommend a DSL for situations with substantial mathematical complexity (not average use cases, but perhaps some financial or academic projects).

With a DSL generation tool such as Xtext, you could define your own simplified mathematical grammar, which could in turn generate a class with containing the Java (or any other language) representation of your formulae.

DSL Expression:

```<code>domain GameMath {
    formula CalcLinearDistance(double): sqrt((x2 - x1)^2 + (y2 - y1)^2)
}
</code>```

Generated Output:

```<code>public class GameMath {
    public static double CalcLinearDistance(int x1, int x2, int y1, int y2) {
        return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    }
}
</code>```

In such a simple example, the benefits of creating the grammar and Eclipse plugin wouldn't be worthwhile, but for more complicated projects, it could yield great benefits, especially if the DSL enabled business folks or academic researchers to maintain formal documents in a comfortable language, and be assured that their work was translated accurately into the project's implementation language.

Body:
In addition to the other good answers here, I might also recommend a DSL for situations with substantial mathematical complexity (not average use cases, but perhaps some financial or academic projects).

With a DSL generation tool such as Xtext, you could define your own simplified mathematical grammar, which could in turn generate a class with containing the Java (or any other language) representation of your formulae.

DSL Expression:

domain GameMath {
    formula CalcLinearDistance(double): sqrt((x2 - x1)^2 + (y2 - y1)^2)
}

Generated Output:

public class GameMath {
    public static double CalcLinearDistance(int x1, int x2, int y1, int y2) {
        return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    }
}

In such a simple example, the benefits of creating the grammar and Eclipse plugin wouldn't be worthwhile, but for more complicated projects, it could yield great benefits, especially if the DSL enabled business folks or academic researchers to maintain formal documents in a comfortable language, and be assured that their work was translated accurately into the project's implementation language.


答:
In principle, I think it makes sense to prevent people from making changes to the mainline which break the build. That is, the process for making changes to main branch of your repository should require ensuring that all tests still pass. Breaking the build is simply too costly in terms of lost time for all engineers on the project to do anything else.

However, the particular solution of commit hooks isn't a good plan.

The developer has to wait for the tests to run while committing. If the developer has to wait on his workstation for all the tests to pass, you've wasted valuable engineer time. The engineer needs to be able to move onto the next task, even if he'll have to switch back because the tests ended up failing.

Developers may want to commit broken code in a branch. In a larger task, the developers version of the code may spend much time not in a passing state. Obviously, merging that code into the mainline would be very bad. But its rather important that the developer can still use version control to track his progress.

There are occasional good reasons to skip the process and bypass the tests.


问:
500 databases or 1 database with 500 tables or just 1 table with all the records?
I currently have an application that is used by a single end customer. For ease of discussion assume the application only needs a single database table for all records. I now need to support multi-tenancy and so in the future I will have about 500 customers using the same database server.

1) A possible solution is to have a separate database for each customer. As there will be around 500 customers that means having MySQL/SQL Server/Oracle/etc... host 500 separate databases. This sounds like overkill for a database server running on an average cloud based server.

2) Another solution is to stick with the single database I already have but to have 500 different tables, one for each end customer. Each customer only averages around 2000 records in their own table. This is easy to implement and I would guess makes it easy to migrate the customer to another server, just move the entire table data over.

3) Lastly I could stick to using a single table in the single database. Instead I add an additional column that identifies the customer the record belongs to. But then the table ends up with about 1,000,000 records which is the aggregate of all 500 customers that average 2,000 each.

I do not know enough about performance and scaling to know 1, 2, 3 is going to give the best performance. Any ideas?

答:
Personally, I'd go with option 3 because:

It is normalized and simple

Easy to query for reports

Easy to back up(just 1 database to worry about)

If you index the table well,  performance shouldn't be an issue

Also, Performance aside, here are some reasons why you would want to avoid option 1 and 2.

Cons if you go with 500 databases, 1 per each customer:

Database Backups will be annoyingly tedious and messy

Cross Database queries are normally a luxury of enterprise database servers, in other words, generating customer reports will be a pain because you can't just have a single query to pull all the relevant customer information in your database

Inelegant

Cons if you go with 500 tables in 1 database, 1 table per customer:

Your database is horribly unnormalized, lots column information duplication going on everywhere

While it is easier to query a lot of tables than to query from different databases, you'd still have to run the same query across god knows how many tables instead of just 1 query


问:
Would forcing developers to fix at 3 AM the build they broke undermine motivation?
Breaking the build is a bad thing. Different teams take different measures to encourage their members to avoid breaking the build at all costs.

Some measures are moderate. For example Joel Spolsky tells that his Excel team had a rule that “whoever broke the build had to babysit the builds until someone else broke it.” (Joel Spolsky. Joel on Software, page 20).

Others are more drastic. For example, Steve McConnell reports that “[s]ome projects have developers wear beepers and require them to fix the build day or night if they are responsible for breaking it.” (Steve McConnell. Rapid Development, page 384)

Forcing the developers to wake up and come to work at the middle of the night to fix the build they've broken looks like an excellent opportunity to focus their attention on the reliability of the code they commit and encourage them to check it twice.

At the same time, programmer analysts usually favor personal life (fourth top priority motivation according to Table 11-1 in Rapid Development page 252, fifteenth for managers and general population) and may not appreciate the risk of hearing their phone ringing at 3 AM.

Personally, it doesn't annoy me to go and fix my mistakes at 3 AM, but only if I work for a company with flexible working hours. Most colleagues I know will refuse to come to work at 3 AM, no matter the reason and no matter how important their presence is for the company.

What is the way of setting up severe measures like night and day beepers while keeping motivation high? Or such drastic measures should be avoided at all costs, and be used only when there are no other choices, to the detriment of the motivation of team members?

答:
Broken builds happen.  It is impossible to completely avoid them.  Developers may be distracted while merging changes, or may simply not have run all of the tests in a very large system where a complete test run may take a significant length of time.  Whatever the reason, it is important to realise you cannot always ensure that they never happen.

Developers don't want to be called back outside of office hours.  I think this is pretty much a given.  Quite aside from any effect on morale, they're likely to do whatever they can to avoid this happening.  As it isn't really possible to 100% ensure that they never break the build, I suspect the effect that this kind of system will have is to make at least some of them reluctant to check in their changes close enough to the end of regular hours that they risk being called back.  If your full integration test suite takes an hour to run, that means people will be reluctant to check in after 4pm, meaning there's a full eighth of the day that they're not checking in for.  This will result in many large check-ins early in the morning, with an increased risk of the build breaking (because the risk is approximately proportional to the size of the check-in).

So, no, I don't think this is a good strategy.  I suspect it will actually have the opposite effect to the intended one.  Joel's suggestion you quote in your question is a much better idea.


答:
I suspect this may be a subjective question, but it's unlikely that forcing people to fix builds late at night/early morning would do anything to improve morale or motivation.

Further, it's likely that work done at 3am is not going to be of the same quality as work done during normal hours, even factoring in programmers' odd schedules. There will also be fewer (if any) people around to do code reviews, or whatever else is part of the bug fix process.

Finally, it seems like a solution to a problem you shouldn't really encounter, with proper environment setup. We use Git along side a CI system that allows branch builds, so that developers are running a build on a CI agent every time they make a commit on their branch (including unit tests). This ensures that when a feature branch is merged into trunk, the code has already been merged (trunk -> feature branch), built and tested on an agnostic system. There are very few legitimate reasons for a build on trunk to fail in this case.

So, in the end, work smarter, not harder.

Title: Would forcing developers to fix at 3 AM the build they broke undermine motivation?

Body:
Breaking the build is a bad thing. Different teams take different measures to encourage their members to avoid breaking the build at all costs.

Some measures are moderate. For example Joel Spolsky tells that his Excel team had a rule that “whoever broke the build had to babysit the builds until someone else broke it.” (Joel Spolsky. Joel on Software, page 20).

Others are more drastic. For example, Steve McConnell reports that “[s]ome projects have developers wear beepers and require them to fix the build day or night if they are responsible for breaking it.” (Steve McConnell. Rapid Development, page 384)

Forcing the developers to wake up and come to work at the middle of the night to fix the build they've broken looks like an excellent opportunity to focus their attention on the reliability of the code they commit and encourage them to check it twice.

At the same time, programmer analysts usually favor personal life (fourth top priority motivation according to Table 11-1 in Rapid Development page 252, fifteenth for managers and general population) and may not appreciate the risk of hearing their phone ringing at 3 AM.

Personally, it doesn't annoy me to go and fix my mistakes at 3 AM, but only if I work for a company with flexible working hours. Most colleagues I know will refuse to come to work at 3 AM, no matter the reason and no matter how important their presence is for the company.

What is the way of setting up severe measures like night and day beepers while keeping motivation high? Or such drastic measures should be avoided at all costs, and be used only when there are no other choices, to the detriment of the motivation of team members?


答:
I guess part of it comes down to personal preferences.

If you handle multiple customers in the same application (i.e. one program receiving requests from multiple customers) I would prefer option 3. Handling multiple customers in this case is part of the application logic, and designed into the data model.

If you run a separate instance of the application for each customer I would initially tend to option 1, since has the best isolation between the customers.

However, with several hundred customers option 1 becomes rather cumbersome since it doesn't scale well, and option 2 is a good compromise.

Title: 500 databases or 1 database with 500 tables or just 1 table with all the records?

Body:
I currently have an application that is used by a single end customer. For ease of discussion assume the application only needs a single database table for all records. I now need to support multi-tenancy and so in the future I will have about 500 customers using the same database server.

1) A possible solution is to have a separate database for each customer. As there will be around 500 customers that means having MySQL/SQL Server/Oracle/etc... host 500 separate databases. This sounds like overkill for a database server running on an average cloud based server.

2) Another solution is to stick with the single database I already have but to have 500 different tables, one for each end customer. Each customer only averages around 2000 records in their own table. This is easy to implement and I would guess makes it easy to migrate the customer to another server, just move the entire table data over.

3) Lastly I could stick to using a single table in the single database. Instead I add an additional column that identifies the customer the record belongs to. But then the table ends up with about 1,000,000 records which is the aggregate of all 500 customers that average 2,000 each.

I do not know enough about performance and scaling to know 1, 2, 3 is going to give the best performance. Any ideas?


答:
No, you shouldn't as other answers have pointed out.

If you want to have a code base that is guaranteed to have no failing tests, you could instead develop on feature branches and do pull requests into master. Then you can define preconditions for accepting those pull requests. The benefit is that you can push really quick and the tests run in the background.


问:
Scenarios for library that will be used by developers
I've started learning BDD but I think I have some misunderstanding of how to use it correctly.

Currently I'm writing an API for a product. This API will be used by other developers only. Is it ok to write features and scenarios from the developer point of view? Something like:

```<code>Feature: Authorization
    In order to access program runtime
    As a module developer
    I want to ensure that authorization is done correctly

Scenario: Login with wrong credentials
    Given I have login "login" and password "pass"
    When I try to login
    Then the exception with message "Some message" must be thrown
</code>```

Or maybe it's better to stick with simple unit testing for such tasks?

答: If the users of your deliverable were dentists, then a scenario would have to be written from the point of view of a dentist, and understandable to him. If the users are all programmers, then it must be written from the viewpoint of a programmer. The fact that programmers will also be the ones who create the system is irrelevant, just like the fact that the programmers of the hypothetical first system also occasionally visit dentists. It's always the role that someone fulfills in a particular interaction that determines what to present and how, not the entirety of their personality.


答:
In C# you could use extension methods.

The below reads pretty nicely once you get used to the "postfix" notation:

```<code>public static class DoubleMathExtensions
{
    public static double Cos(this double n)
    {
        return Math.Cos(n);
    }

    public static double Sin(this double n)
    {
        return Math.Sin(n);
    }

    ...
}

var x =  -X.Cos() * Z.Sin() + X.Sin() * Y.Sin() * Z.Cos();
</code>```

Unfortunately operator precedence makes things a bit uglier when dealing with negative numbers here. If you want to calculate Math.Cos(-X) instead of -Math.Cos(X) you will need to enclose the number in parenthesis:

```<code>var x = (-X).Cos() ...
</code>```

Body:
In C# you could use extension methods.

The below reads pretty nicely once you get used to the "postfix" notation:

public static class DoubleMathExtensions
{
    public static double Cos(this double n)
    {
        return Math.Cos(n);
    }

    public static double Sin(this double n)
    {
        return Math.Sin(n);
    }

    ...
}

var x =  -X.Cos() * Z.Sin() + X.Sin() * Y.Sin() * Z.Cos();

Unfortunately operator precedence makes things a bit uglier when dealing with negative numbers here. If you want to calculate Math.Cos(-X) instead of -Math.Cos(X) you will need to enclose the number in parenthesis:

var x = (-X).Cos() ...