问:
Using a masterID in sql to merge different item types
I am designing tables in sql for a small ticketing system. One of the demands is that a user/agent can post a ticket to either a department or an agent.

Now if I have a child parent table where each agent belongs to one department, I would end up with a limitation that one agent could be assigned to one department. I don't think it would be a good idea for one child to have multiple parents.

I am basically stuck at this point since each ticket would have an assignee in the form of AssigneeID. The only option that comes to my mind is to create three tables

```<code>table Agents
columns AgentID, AssigneeID

table Departments
columns DepartmentID, AssigneeID

table Assignees
columns AssigneeID, AssigneeTypeID
</code>```

from where I would get unique assigneeID and later on try to connect it to department or an agent.

Is there a better way to do this?

答:
There are a number of options:

1) use a UNIQUEIDENTIFIER for the assignment field of the Ticket. Each Assignable would need to have their own UNIQUEIDENTIFIER to link them. Nothing really to keep UUIDs unique across the two tables, though.

2) your parent/child table could be multiplexed:

The TicketId has a UNIQUE constraint on it, so that it may only be assigned at most once.
There is an AgentId and DepartmentId nullable fields, and a check constraint to ensure only one of them is set at a time.

If a ticket MUST be assigned, then simply put the DepartmentId and AgentId fields into the ticket itself.

Downside... if you add a third type of thing that is assignable, you have to add columns to a table that is likely to have a lot of rows.

3) table per type(which is basically what you're suggesting in your post)

Ticket has (at the minimum) an Id and a AssignmentType.  There is a PK on Id, and a UQ on Id and AssignmentType.

AssignmentType is FK to a table called AssignmentTypes, which just have Ids with records with 1 and 2 in it.

Two more tables:  AgentAssignment: (Id(FK->Ticket.Id), AssignmentType as 1 PERSISTED NOT NULL, AgentId)
DepartmentAssignment (Id(FK->Ticket.Id), AssignmentType as 2 PERSISTED NOT NULL, DepartmentId)


问:
Where should my team start with becoming "modern"?
I'm a relatively new developer, fresh from college. While in college and during subsequent job-seeking, I realized that there were a lot of "modern" software development methodologies that my education was lacking: unit testing, logging, database normalization, agile development (vs. generic agile concepts), coding style guides, refactoring, code reviews,  no standardized documentation methods (or even requirements), etc.

Overall, I didn't see this is a problem. I expected my first job to embrace all of these ideas and to teach them to me on the job. Then I got my first job (full stack web development) at a big corporation and I realized that we do none of these things. In fact I, the least experienced on the team, am the one who is spearheading attempts to bring my team up to speed with "modern" programming techniques - as I worry that not doing so is professional suicide down the road.

First I began with logging software (log4J), but then I quickly moved on to writing my own styleguide, then abandoning it for the Google styleguide - and then I realized that our Java web development used hand-written front controllers, so I pushed for our adoption of Spring - but then I realized we had no unit tests, either, but I was already learning Spring... and as you can see, it becomes overwhelming all too quickly, especially when paired with normal development work. Furthermore, it is difficult for me to become "expert" enough in these methodologies to teach anyone else in them without devoting too much time to a single one of them, let alone them all.

Of all these techniques, which I see as "expected" in today's software development world, how do I integrate them into a team as a new player without overwhelming both myself and the team?

How can I influence my team to become more agile? is related, but I'm not an Agile developer like the asker here, and I'm looking at a much broader set of methodologies than Agile.

答:
I hope you have not presented the issues to your coworkers as you did to us in your post. THAT would be professional suicide.

The first issue is that you are trying to teach technologies and methods that even you do not have experience with to a group of programmers that, maybe are a little outdated, but get the job "done". The possibilities of that backfiring are endless, and will probably bring a lot of joy to your coworkers. It is interesting and admirable that you want to improve yourself and your department, but avoid using terms like "spearheading". Sincerely, don't use that word.

As a side issue to the above, check that you are doing some work. I have been working as a lone, self-learning programmer for a lot of time, and I know how easy is to set aside the actual work in order to explore promising frameworks, technologies and the like. Ensure yourself that your performance is within the expected parameters (no, nobody cares that you spend 20 hours researching Spring if that report they asked you is not done).

From all of the above, avoid being the teacher (unless it is related to a field/tech in which actually you have enough experience). A more neutral presentation would be pointing the advantages of, say, automated testing, and letting management chose who they want to research the pros and cons of those practices.

Now, for presenting those "best practices", there are two ways of explaining them to your team:

Because I say that they are the best practices, and that is enough.

Because they are useful and help solve problem.

Using the first argument, unless you are the boss or a very senior member of the team, it is unlikely that they will give you any attention. And "I read a book from Knuth that says so" or "the guys of the SE say that" will not cause any impression, neither ("those guys do not work here so they do not really know what is good for this IT shop"). They have their methods, routines, procedures, and things "more or less" work, so why take the effort and risks of changing?

For the second approach to work, there must be the realization that a problem exists. So:

don't go pushing day and night for automatic testing. Wait until an update breaks some features, and the team has to work overtime to fix it, and then propose to build an automated test system.

don't ask for code reviews. Wait until Joe is in a extended leave and there is a need to change in that module that only Joe knows about, and point to your boss how much time was lost just trying to understand Joe's code.

Of course, change will be slow and progressive (more so in a big corporation). If you get to introduce code review and automated testing in five years, you should congratulate yourself on a work well done. But, unless there is a complete rewrite due to external causes, forget about any fantasy that they will switch the core IS to, say, Spring (Joel explained that way better than I ever could, even before you were born1); in that time you could, at most, get Spring in the list of supported platforms to write non-critical systems.

Welcome to the world of enterprise IT, boy! :-p

1: Ok, maybe I am exagerating a little, but not too much.

ContentLicense: CC BY-SA 3.0


问:
Is this a good method to create class hierarchies?
Is it a good design to store the type of the object in the base class as an enum? For example, consider the following hierarchy

```<code>Expr
--Unary
--Binary
--Const
----Int
----Float
</code>```

How to represent the above hierarchy in C++, so that I can inspect the type of an object of a subclass.

```<code>enum ExprType {
   Const, Binary, Unary
};

class Expr {
   ExprType type;
public:
   Expr(ExprType t) : type(t) { }
   ExprType GetType() { return type; }
};

class BinNode: public Expr {
   Expr* left, *right;
   Operator op;
public:
   BinNode() : Expr(ExprType::Binary) { }
};

class UnrNode: public Expr {
   Expr* operand;
   Operator op;
public:
   UnrNode() : Expr(ExprType::Unary) { }
};

enum ConstNodeType {
   Int, Float
};

class ConstNode: public Expr {
   ConstNodeType cntype;
public:
   ConstNode(ConstNodeType t) : Expr(ExprType::Const), cntype(t) { }
   ConstNodeType GetConstType() { return cntype; }
};

class IntNode: public ConstNode {
   int value;
public:
   IntNode() : ConstNode(ConstNodeType::Int) { }
};

class FloatNode: public ConstNode {
   float value;
public:
   FloatNode() : ConstNode(ConstNodeType::Float) { }
};
</code>```

Now I can do,

```<code>Expr* node = new IntNode();
node->GetType(); // returns ExprType::Const
node->GetConstType(); // return ConstNodeType::Int
</code>```

Is this is good idiomatic way to create a hierarchy of classes? I basically want to check the type of an object of any subclass of Expr.

I can do it in C# using the is operator without a special type member.

```<code>Expr node = new IntNode();
assert(node is ConstNode);
assert(node is IntNode);
</code>```

In C++, I can use RTTI, but is this the idiomatic way to create a class of hierarchies? Is there any alternative way to express the same hierarchy?

答:
Whenever you feel an urge to inspect the dynamic type of your polymorphic objects at run-time, you should question your design.  This is true for any object-oriented language I know.  The visitor pattern can be of great help in avoiding to bother with the dynamic type of an object.

Some people seem to think that cheating around type inspection by adding a tag to each object will make for a better design.  I strongly disagree with these people.  If you cannot (or are not willing to) avoid the run-time type inspection, admit it and use the (presumably most efficient) mechanisms for doing this provided natively by the language.  Adding a type tag only increases run-time overhead and generally makes the code more complex introducing a new chance to add bugs.

Given the following hierarchy

```<code>struct Base { virtual ~Base(); };
struct Derived : Base { void foo(); };
</code>```

and a pointer p to Base, the idiomatic way to check whether it actually points to a Derived object is to try a dymanic_cast like so:

```<code>bool
is_this_a_derived(Base * p)
{
  return dynamic_cast<Derived *>(p);
}
</code>```

The dynamic_cast will return a Derived pointer to the object if it is one and a nullptr otherwise.  The implicit conversion to bool will do the correct thing, then.

If you want, you can encapsulate this into a generic template

```<code>template <typename BaseT, typename DerivedT>
bool
is_instance_of(const BaseT * p) noexcept
{
  return dynamic_cast<const DerivedT *>(p);
}
</code>```

and use it like this.  Though personally I'd question the usefulness of this.

```<code>void
example(Base * p)
{
  if (is_instance_of<Derived>(p))
    std::cout << "We have a derived thing here.\n";
  else
    std::cout << "This thing is not derived.\n";
}
</code>```

Often times, you will probably want to do something specific to the derived class.  For example, invoke its foo member function in this example.  The idiomatic way to do this would look like this:

```<code>void
invoke_foo_if_this_is_a_derived(Base * basep)
{
  if (auto derivedp = dynamic_cast<Derived *>(basep))
    derivedp->foo();
}
</code>```

The code uses the fact that I can limit the scope of the derivedp to the body of the if statement – the only place where it is useful and guaranteed to be not a nullptr.

For these examples to work, it is crucial that Base has at least one virtual member.  Usually, you will want to make at least the destructor of the base class virtual because otherwise deleteing a derived object through a base class pointer would invoke undefined behavior.  The code in your question is therefore not safe (unless you plan to leak everything anyway) because Expr has no virtual destructor.

Body:
Whenever you feel an urge to inspect the dynamic type of your polymorphic objects at run-time, you should question your design.  This is true for any object-oriented language I know.  The visitor pattern can be of great help in avoiding to bother with the dynamic type of an object.

Some people seem to think that cheating around type inspection by adding a tag to each object will make for a better design.  I strongly disagree with these people.  If you cannot (or are not willing to) avoid the run-time type inspection, admit it and use the (presumably most efficient) mechanisms for doing this provided natively by the language.  Adding a type tag only increases run-time overhead and generally makes the code more complex introducing a new chance to add bugs.

Given the following hierarchy

struct Base { virtual ~Base(); };
struct Derived : Base { void foo(); };

and a pointer p to Base, the idiomatic way to check whether it actually points to a Derived object is to try a dymanic_cast like so:

bool
is_this_a_derived(Base * p)
{
  return dynamic_cast<Derived *>(p);
}

The dynamic_cast will return a Derived pointer to the object if it is one and a nullptr otherwise.  The implicit conversion to bool will do the correct thing, then.

If you want, you can encapsulate this into a generic template

template <typename BaseT, typename DerivedT>
bool
is_instance_of(const BaseT * p) noexcept
{
  return dynamic_cast<const DerivedT *>(p);
}

and use it like this.  Though personally I'd question the usefulness of this.

void
example(Base * p)
{
  if (is_instance_of<Derived>(p))
    std::cout << "We have a derived thing here.\n";
  else
    std::cout << "This thing is not derived.\n";
}

Often times, you will probably want to do something specific to the derived class.  For example, invoke its foo member function in this example.  The idiomatic way to do this would look like this:

void
invoke_foo_if_this_is_a_derived(Base * basep)
{
  if (auto derivedp = dynamic_cast<Derived *>(basep))
    derivedp->foo();
}

The code uses the fact that I can limit the scope of the derivedp to the body of the if statement – the only place where it is useful and guaranteed to be not a nullptr.

For these examples to work, it is crucial that Base has at least one virtual member.  Usually, you will want to make at least the destructor of the base class virtual because otherwise deleteing a derived object through a base class pointer would invoke undefined behavior.  The code in your question is therefore not safe (unless you plan to leak everything anyway) because Expr has no virtual destructor.


问:
Is it okay to go against all-caps naming for enums to make their String representation simpler?
Several times I've seen people use title-case or even all lower-case naming for enum constants, for example:

```<code>enum Color {
  red,
  yellow,
  green;
}
</code>```

This makes working with their string form simple and easy, if you want to do throw new IllegalStateException("Light should not be " + color + "."), for example.

This seems more acceptable if the enum is private, but I still don't like it.  I know I can make an enum constructor with a String field, and then override toString to return that name, like this:

```<code>enum Color {
  RED("red"),
  YELLOW("yellow"),
  GREEN("green");

  private final String name;

  private Color(String name) {
    this.name = name
  }

  @Override public String toString() {
    return name;
  }
}
</code>```

But look how much longer that is.  It's annoying to keep doing if you have a bunch small enums you want to keep simple.  Is it okay to just use unconventional case formats here?

答:
Don't modify ENUM that's just bad code smell. Let an enum be an enum and a string be a string.

Instead, use a CamelCase converter for string values.

```<code>throw new IllegalStateException("Light should not be " + CamelCase(color) + ".");
</code>```

There are many open source libraries that already solve this issue for Java.

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/CaseFormat.html

Body:
Don't modify ENUM that's just bad code smell. Let an enum be an enum and a string be a string.

Instead, use a CamelCase converter for string values.

throw new IllegalStateException("Light should not be " + CamelCase(color) + ".");

There are many open source libraries that already solve this issue for Java.

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/CaseFormat.html


答:
If Agents had no associations to Department, i would do this :

```<code>table Agents
AgentID PK

table Departments
DepartmentId PK

table Tickets
AssigneeID FK to (AgentID OR DepartmentId)
AssigneeType ('Agent' or 'Department')
</code>```

Then you can do :

```<code>Select
     t.*
     ,coalese(a.name,d.name) as AssigneeName
from Tickets t
left join Agents a on a.AgentID =t.AssigneeID and t.AssigneeType ='Agent'
left join Departments d on d.DepartmentId=t.AssigneeID and t.AssigneeType ='Department'
</code>```

But my understating from your description is that an Agent is part of a department.  Because of this i think your design should be as follows:

```<code>table Departments
DepartmentID PK

table Agents
AgentID
CurrentDepartmentID FK

table Tickets
AgentID FK (Optional)
DepartmentID FK (Required)
</code>```

IF the User selects and Agent, the DepartmentID  should be auto populated by the Agent's CurrentDepartmentID. The reason you don't simply pull this data via a join is because an agent may move departments and the Ticket must remain with the department even agent moves.

Title: Using a masterID in sql to merge different item types

Body:
I am designing tables in sql for a small ticketing system. One of the demands is that a user/agent can post a ticket to either a department or an agent.

Now if I have a child parent table where each agent belongs to one department, I would end up with a limitation that one agent could be assigned to one department. I don't think it would be a good idea for one child to have multiple parents.

I am basically stuck at this point since each ticket would have an assignee in the form of AssigneeID. The only option that comes to my mind is to create three tables

```<code>table Agents
columns AgentID, AssigneeID

table Departments
columns DepartmentID, AssigneeID

table Assignees
columns AssigneeID, AssigneeTypeID
</code>```

from where I would get unique assigneeID and later on try to connect it to department or an agent.

Is there a better way to do this?

Body:
If Agents had no associations to Department, i would do this :

table Agents
AgentID PK

table Departments
DepartmentId PK

table Tickets
AssigneeID FK to (AgentID OR DepartmentId)
AssigneeType ('Agent' or 'Department')

Then you can do :

Select
     t.*
     ,coalese(a.name,d.name) as AssigneeName
from Tickets t
left join Agents a on a.AgentID =t.AssigneeID and t.AssigneeType ='Agent'
left join Departments d on d.DepartmentId=t.AssigneeID and t.AssigneeType ='Department'

But my understating from your description is that an Agent is part of a department.  Because of this i think your design should be as follows:

table Departments
DepartmentID PK

table Agents
AgentID
CurrentDepartmentID FK

table Tickets
AgentID FK (Optional)
DepartmentID FK (Required)

IF the User selects and Agent, the DepartmentID  should be auto populated by the Agent's CurrentDepartmentID. The reason you don't simply pull this data via a join is because an agent may move departments and the Ticket must remain with the department even agent moves.


问:
UML diagram for attributes that can have two different types
I have been to an interview for a financial programming job, and I could not answer to one question for sure. I thought about it again, but I really cannot find a good answer.

They asked me to design the UML diagram for a class Instrument (financial instrument, such as bond or stock), which has a price, a type which can only be "Forex" or "Rate", and a notional which can either be a double or a double + array of object.

The price is not a problem, it's just a double.

But I'm stuck on the type : I thought to an enum and to a boolean, but I'm really not sure it's the best way to do it

and on the notional : I designed another class for that, with a double attribute and an optional array of object attribute. But this is also really ugly.

What would be the good way of solving this problem?

Thank you for your help

答:
The presence of a type attribute is a bit of a concern for me. The fact that there can be different types of Instruments implies that there should be an abstract Instrument interface, with common methods declared, and multiple concrete implementations (stock, bond, etc.). The forex/rate type may fall into this category, or it may not. I don't know enough about financial instruments to make a good choice here. Perhaps the question was really seeking to prompt you to ask more about the domain?

In general, giving objects type attributes is something I try to avoid. If you put them in, then you presumably will have code outside the class that behaves differently depending on the type of the object being used. This violates the idea that in OOD you let the object do the work (passing in any extra information needed), not the code that uses the object. In other words, type attributes defeat the purpose of polymorphism. In any event, the compiler usually provides type information automatically for all objects. Can you use that?

Sometimes type attributes make sense, for example if you want to gather some statistics on a collection of polymorphic objects (20% stocks, 35% bonds, 40% forex, 10% rate, etc.).

Not knowing much about what a "notional" is, I think your solution to have a class with a double and optional array is a reasonable choice. I see no reason why the degenerate case of a notional with an empty array is any less valid than one with a nonempty array.

If you absolutely have to have a type attribute for forex and rate, I would go with an enum. First, just because it can only be one of two things now does not mean that more things won't be needed later (what about options, derivatives, credit default swaps, etc.?). Second, if you go with a boolean, where true means forex and false means rate, then you are implicitly saying that an Instrument which is "not forex" is a rate Instrument. This is not quite the same thing as explicitly saying an Instrument is a rate Instrument. By conflating "not forex" and rate, you prevent the concepts from being separate in the future.

The conclusion I am coming to is that the overarching Instrument class should be a weak one. There is so much variation in the specializations of it that it makes little sense to push much functionality and attributes into the superclass. It's kind of like putting cars, planes, boats, and trains into a Vehicle class. There's not much you can put there beyond carrying capacity and weight, and the fact that instances of each are all Vehicles. Better to let the individual Instrument types stand on their own, loosely collected under the Instrument class.


答:
If there is the slightest chance that these string representations might be stored in places like databases or text files, then having them tied to the actual enum constants will become highly problematic if you ever need to refactor your enum.

What if one day you decide to rename Color.White to Color.TitaniumWhite while there are data files out there containing "White"?

Also, once you start converting enum constants to strings, the next step further down the road will be to generate strings for the user to see, and the problem here is, as I am sure you already know, that the syntax of java does not allow spaces within identifiers. (You will never have Color.Titanium White.)  So, since you will probably need a proper mechanism for generating enum names to show to the user, it is best to avoid unnecessarily complicating your enum.

That having been said, you can of course go ahead and do what you have been thinking of doing, and then refactor your enum later, to pass names to the constructor, when (and if) you run into trouble.

You can shave a couple of lines off your enum-with-constructor by declaring the name field public final and losing the getter.  (What is this love that java programmers have towards getters?)

Title: Is it okay to go against all-caps naming for enums to make their String representation simpler?

Body:
Several times I've seen people use title-case or even all lower-case naming for enum constants, for example:

```<code>enum Color {
  red,
  yellow,
  green;
}
</code>```

This makes working with their string form simple and easy, if you want to do throw new IllegalStateException("Light should not be " + color + "."), for example.

This seems more acceptable if the enum is private, but I still don't like it.  I know I can make an enum constructor with a String field, and then override toString to return that name, like this:

```<code>enum Color {
  RED("red"),
  YELLOW("yellow"),
  GREEN("green");

  private final String name;

  private Color(String name) {
    this.name = name
  }

  @Override public String toString() {
    return name;
  }
}
</code>```

But look how much longer that is.  It's annoying to keep doing if you have a bunch small enums you want to keep simple.  Is it okay to just use unconventional case formats here?


问:
What is the function of URLs as "key" names in markup used for a RESTful API?
I just finished reading REST in Practice as my first* introduction to REST APIs. I found the book quite enlightening, but am left with one nagging question, and Google has yet to clear it up. This question gets close, but the answers fall short of answering my specific question, which is...

Given some hypertext markup for consumption with a RESTful API, such as this (in JSON-LD):

{
  "http://schema.org/name": "Manu Sporny",
  "http://schema.org/url": { "@id": "http://manu.sporny.org/" },
  "http://schema.org/image": { "@id": "http://manu.sporny.org/images/manu.png" }
}
```

What is the function of the URL/URI/IRI as a "key" name?  (Now I know that JSON-LD--with @context--and other markup languages, allow ways to generalize these IRIs-as-keys to be more human friendly, but that doesn't change the nature of the question.)

If I try to break my question down into smaller pieces, I come up with something like this:

Specifically, what is expected to live at the endpoint represented by that IRI?

All the discussion talks about disambiguating key names. But how is http://schema.org/name less ambiguous than name?

Is there some (theoretical?) centralized repository of key types that developers are expected to reference, so that these key names all point to some more-or-less common definition?

I hope this question makes enough sense to be answerable. I'm still in a bit of a "I don't know enough to ask what I don't know" state on this particular point.

*I, like many, thought I already knew what REST was, and believed that my previous, POST-only CGI scripts were representative of REST APIs...

答:
What is the function of the URL/URI/IRI as a "key" name?

The answer can be found in RFC 5988 (Chapter 5.3. Relation Type):

```<code>Note that extension relation types are REQUIRED to be absolute URIs...
</code>```

Simply put, the "keys" you are referring to are called "relations" and in order to be uniquely identified, you can either use any of the standardized ones (like self, author, stylesheet, etc) or you can introduce custom ones, in which case you need to namespace (prefix) them in such a way that noone else creates the same named relation that means something else. This is done by using a relation name in a form of an absolute URI, as mentioned in that RFC document.

Body:
What is the function of the URL/URI/IRI as a "key" name?

The answer can be found in RFC 5988 (Chapter 5.3. Relation Type):

Note that extension relation types are REQUIRED to be absolute URIs...

Simply put, the "keys" you are referring to are called "relations" and in order to be uniquely identified, you can either use any of the standardized ones (like self, author, stylesheet, etc) or you can introduce custom ones, in which case you need to namespace (prefix) them in such a way that noone else creates the same named relation that means something else. This is done by using a relation name in a form of an absolute URI, as mentioned in that RFC document.


答:
No, this is not idiomatic. If you absolutely must cast from base type to derived type, use the RTTI mechanism provided by the language. But first, question why you want to do that at all!

In most instances you shouldn't need to care what the type of the object is, you should be calling virtual member functions that the derived type implements to do the right thing for its type.

Title: Is this a good method to create class hierarchies?

Body:
Is it a good design to store the type of the object in the base class as an enum? For example, consider the following hierarchy

```<code>Expr
--Unary
--Binary
--Const
----Int
----Float
</code>```

How to represent the above hierarchy in C++, so that I can inspect the type of an object of a subclass.

```<code>enum ExprType {
   Const, Binary, Unary
};

class Expr {
   ExprType type;
public:
   Expr(ExprType t) : type(t) { }
   ExprType GetType() { return type; }
};

class BinNode: public Expr {
   Expr* left, *right;
   Operator op;
public:
   BinNode() : Expr(ExprType::Binary) { }
};

class UnrNode: public Expr {
   Expr* operand;
   Operator op;
public:
   UnrNode() : Expr(ExprType::Unary) { }
};

enum ConstNodeType {
   Int, Float
};

class ConstNode: public Expr {
   ConstNodeType cntype;
public:
   ConstNode(ConstNodeType t) : Expr(ExprType::Const), cntype(t) { }
   ConstNodeType GetConstType() { return cntype; }
};

class IntNode: public ConstNode {
   int value;
public:
   IntNode() : ConstNode(ConstNodeType::Int) { }
};

class FloatNode: public ConstNode {
   float value;
public:
   FloatNode() : ConstNode(ConstNodeType::Float) { }
};
</code>```

Now I can do,

```<code>Expr* node = new IntNode();
node->GetType(); // returns ExprType::Const
node->GetConstType(); // return ConstNodeType::Int
</code>```

Is this is good idiomatic way to create a hierarchy of classes? I basically want to check the type of an object of any subclass of Expr.

I can do it in C# using the is operator without a special type member.

```<code>Expr node = new IntNode();
assert(node is ConstNode);
assert(node is IntNode);
</code>```

In C++, I can use RTTI, but is this the idiomatic way to create a class of hierarchies? Is there any alternative way to express the same hierarchy?


答:
Sending enums between my Java code and a database or client app, I often end up reading and writing the enum values as strings.  toString() is called implicitly when concatenating strings.  Overriding toString() on some enums meant that that sometimes I could just

```<code>"<input type='checkbox' value='" + MY_CONST1 + "'>"
</code>```

and sometimes I had to remember to call

```<code>"<input type='checkbox' value='" + MY_CONST1.name() + "'>"
</code>```

which led to errors, so I don't do that anymore.  Actually, I don't override any methods on Enum because if you throw them around to enough client code, you'll eventually break someone's expectations.

Make your own new method name, like public String text() or toEnglish() or whatever.

Here is a little helper function that could save you some typing if you have lots of enums like the above:

```<code>public static String ucFirstLowerRest(String s) {
    if ( (s == null) || (s.length() < 1) ) {
        return s;
    } else if (s.length() == 1) {
        return s.toUpperCase();
    } else {
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    }
}
</code>```

It's always easy to call .toUpperCase() or .toLowerCase() but getting back mixed-case can be tricky.  Consider the color, "bleu de France."  France is always capitalized, so you may want to add a textLower() method to your enum if you run into that.  When you use this text at the beginning of a sentence, vs. the middle of a sentence, vs. in a title, you can see how a single toString() method is going to fall short.  And that doesn't even touch characters that are illegal in Java identifiers, or that are a pain to type because they aren't represented on standard keyboards, or characters that don't have case (Kanji, etc.).

```<code>enum Color {
  BLEU_DE_FRANCE {
    @Override public String textTc() { return "Bleu De France"; }
    @Override public String textLc() { return "bleu de France"; }
  }
  CAFE_NOIR {
    @Override public String textTc() { return "Café Noir"; }
  }
  RED,
  YELLOW,
  GREEN;

  // The text in title case
  private final String textTc;

  private Color() {
    textTc = ucFirstLowerRest(this.toString());
  }

  // Title case
  public String textTc() { return textTc; }

  // For the middle of a sentence
  public String textLc() { return textTc().toLowerCase(); }

  // For the start of a sentence
  public String textUcFirst() {
    String lc = textLc();
    return lc.substring(0, 1).toUpperCase() + lc.substring(1);
  }
}
</code>```

It is not so difficult to use these properly:

```<code>IllegalStateException(color1.textUcFirst() + " clashes horribly with " +
                      color2.textLc() + "!")
</code>```

Hopefully that also demonstrates why using mixed-case enum values will disappoint you as well.  One last reason to keep with all-caps with underscores enum constants is that doing so follows the Principle of Least Astonishment.  People expect it, so if you do something different, you are always going to have to be explaining yourself, or dealing with people misusing your code.

Body:
Sending enums between my Java code and a database or client app, I often end up reading and writing the enum values as strings.  toString() is called implicitly when concatenating strings.  Overriding toString() on some enums meant that that sometimes I could just

"<input type='checkbox' value='" + MY_CONST1 + "'>"

and sometimes I had to remember to call

"<input type='checkbox' value='" + MY_CONST1.name() + "'>"

which led to errors, so I don't do that anymore.  Actually, I don't override any methods on Enum because if you throw them around to enough client code, you'll eventually break someone's expectations.

Make your own new method name, like public String text() or toEnglish() or whatever.

Here is a little helper function that could save you some typing if you have lots of enums like the above:

public static String ucFirstLowerRest(String s) {
    if ( (s == null) || (s.length() < 1) ) {
        return s;
    } else if (s.length() == 1) {
        return s.toUpperCase();
    } else {
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    }
}

It's always easy to call .toUpperCase() or .toLowerCase() but getting back mixed-case can be tricky.  Consider the color, "bleu de France."  France is always capitalized, so you may want to add a textLower() method to your enum if you run into that.  When you use this text at the beginning of a sentence, vs. the middle of a sentence, vs. in a title, you can see how a single toString() method is going to fall short.  And that doesn't even touch characters that are illegal in Java identifiers, or that are a pain to type because they aren't represented on standard keyboards, or characters that don't have case (Kanji, etc.).

enum Color {
  BLEU_DE_FRANCE {
    @Override public String textTc() { return "Bleu De France"; }
    @Override public String textLc() { return "bleu de France"; }
  }
  CAFE_NOIR {
    @Override public String textTc() { return "Café Noir"; }
  }
  RED,
  YELLOW,
  GREEN;

  // The text in title case
  private final String textTc;

  private Color() {
    textTc = ucFirstLowerRest(this.toString());
  }

  // Title case
  public String textTc() { return textTc; }

  // For the middle of a sentence
  public String textLc() { return textTc().toLowerCase(); }

  // For the start of a sentence
  public String textUcFirst() {
    String lc = textLc();
    return lc.substring(0, 1).toUpperCase() + lc.substring(1);
  }
}

It is not so difficult to use these properly:

IllegalStateException(color1.textUcFirst() + " clashes horribly with " +
                      color2.textLc() + "!")

Hopefully that also demonstrates why using mixed-case enum values will disappoint you as well.  One last reason to keep with all-caps with underscores enum constants is that doing so follows the Principle of Least Astonishment.  People expect it, so if you do something different, you are always going to have to be explaining yourself, or dealing with people misusing your code.


问:
HTTP API Versioning and Need to Introduce Breaking Changes to All Supported Versions
I am developing an HTTP application and deploying this by versioning it against the semantic versioning patterns/techniques/whatever they are. In order not to break existing clients and allow the releases to be flexible, there are several rules for the releases:

At the same time, it supports two major versions. E.g. 2.3.4 and 3.4.5 can be both supported at the same time but there will be no 2.3.4, 3.4.5, 4.5.6 support for instance.

It's possible to apply an hot-fix to supported lower version of the HTTP application. E.g, I have two versions of the HTTP application running: 2.3.4 and 3.4.5. I will apply an hot-fix on 2.3.4 release and bump its version to 2.3.5.

This scenario mostly covers all of my needs except for where I need to apply a change to both versions at the same time and that change introduces a breaking change. For example, consider the following scenario:

Version 2.3.4 and 3.4.5 of the application are running. We discovered a security bug and fixing that bug will introduce a breaking change to two of deployed versions. In ideal scenario, I would be version the new release as 4.0.0 and retire the 2.3.4 release. So, 4.0.0 and 3.4.5 will be the supported versions but in this case, 3.4.5 needs to be retired as well as it has security hole.

How would you cover this case or how are you handling it today if you have a similar application and deployment structure? We haven't come across to a scenario like this yet but I really don't want to continue my life with a question mark like this :)

Update:

Why are you originally supporting two different builds?

Several reasons:

This HTTP service backs more than one client (let's say thousands). So, it's not possible to update them simultaneously. Classic reason why you want to version your stuff.

Let's assume that only consumer of this HTTP service is me. Even with that, it's not possible for me to update my clients and the HTTP application simultaneously. So, I again need versioning. If this was the case, the above scenario would be less of a problem as I am controlling all the clients.

答:
I think in order to answer this question, you need to ask yourself another more important question...

Why are you originally supporting two different builds?

Most likely the answer to that would be because you have customers that have a different tempo at introducing newer major versions, which makes complete sense.  So a customer is on 2.3.4 and haven't yet migrated to 3.4.5 because of operations, testing, etc.  Whatever the reason, they are slower to adopt.  Perhaps this customer implements every other major release.

But in the case of your hotfix causes the absolutely need for a breaking change to both current versions (provided that breaking change is a must).  In this case, it would only make sense to increment your major of the build, and have a single build going forward until a secondary major release becomes in support (to then continue following your model of two supported builds for supportability).

The reason I say this is because the benefit of supporting an older major release for customers is no longer there, as you're forcing them to adopt breaking changes in a newer major version.

So in my opinion, this would be a good reason to have a point of convergence to a single supported build until your next natural progression of another major release comes about, in which case you would have your two supported builds again.

After the breaking changes, you'd have version 4.0.0 as the only supported build.  And then you would eventually have your 5.x.x build, in which case you would now be supporting both 4.x.x and 5.x.x.


问:
When should I use C#'s implicit type conversion operator?
In C#, we can overload the implicit conversion operator like this (example from MSDN):

```<code>struct Digit
{
    /* ... */
    public static implicit operator byte(Digit d)  // implicit digit to byte conversion operator
    {
        /* ... */
    }
}
</code>```

Thus, we can have a type, a custom value type, magically converting itself to another (unrelated) type, leaving the audience in bewilderment (until they peer into the backstage and see the implicit conversion operator, that is).

I don't like leaving anyone who reads my code in bewilderment. I don't think many people do.

The question is, what are the use-cases of the implicit type conversion operator which won't render my code much more difficult to understand?

答:
The question is, what are the use-cases of the implicit type conversion operator which won't render my code much more difficult to understand?

When the types aren't unrelated (to programmers). There are (rare) scenarios where you have two unrelated types (as far as the code is concerned), that are actually related (as far as the domain or reasonable programmers) are concerned.

For example, some code to do string matching. A common scenario is to match a string literal. Rather than calling IsMatch(input, new Literal("some string")), an implicit conversion lets you get rid of that ceremony - the noise in the code - and focus on the string literal.

Most any programmer will see IsMatch(input, "some string") and quickly intuit what is going on. It makes your code clearer at the call site. In short, it makes it a bit easier to understand what is going on, at a slight expense of how that is going on.

Now, you might argue that a simple function overload to do the same thing would be better. And it is. But if this sort of thing is ubiquitous, then having one conversion is cleaner (less code, increased consistency) than doing a pile of function overloads.

And you might argue that it is better to require programmers to explicitly create the intermediate type so they see "what is really going on". That is less straightforward. Personally, I think that the literal string match example is very clear about "what is really going on" - the programmer needs not know the mechanics of how everything happens. Do you know how all your code is executed by the various processors your code runs on? There is always a line of abstraction where programmers stop caring about how something works. If you think that the implicit conversion steps are important, then don't use the implicit conversion. If you think they're just ceremony to keep the computer happy, and the programmer would be better off not seeing that noise everywhere, then consider it.


问:
Problems with OO design for application with pluggable components
I'm trying to refactor an ugly code and make it easly extendable in the future.

The application should be nothing else but a series of components that have input(s) and output(s). The components are chained in such manner that the current component's input is the output of one (or more) previous components.

Here's a quick overview of what I have so far:

Reader

Denotes a data source

Can be a file on HDD, online resource, database, etc.

Splitter

Input is Reader(s)

Splits the contents of what reader delivers into parts

Outputs are split contents of Reader(s)

Model

Input is Splitter(s)

Creates a model of something based on Splitter(s) outputs

Output is silent, but you can say that the output is an internal state that can be queried for individual inputs

Tester

Input is a model

It can query a model for a result on some data

Output is optional, but in case it is used, it's a stream of (queryInput, queryOutput) data

Writer

Input is practiacally anything that produces a collection of objects

Writes that collection to wherever

I dunno what the output should be right now

So, I want to do have the ability to plug them in the following manner:

-->Reader-->Splitter-->Model-->Tester-->Writer-->

However, this would also be a valid combination (it obviously does nothing more but a simply data transfer)

-->Reader-->Writer-->

Now, since I'd like to be able to plug (almost) everything to everything and (possibly) create quite long chains, I'd assume I'd have to have some sort of Pluggable interface.

Also, when creating such big chain, I'd probably want to wrap it behind a Facade. And since I'd want each pluggable component (class) to be replaced by some other, then Strategy pattern comes to mind.

Now, since I've already mentioned the term chain here, Chain of Responsibility pattern comes to my mind, in the following (or similar way):

```<code>public interface Pluggable<InputType, OutputType> {
    public void consume(Pluggable<?, InputType> previous);
    public Collection<OutputType> produce();
}
</code>```

For example, if I wanted to have my Splitter to split a list of Files provided by Reader, it might looks something like this:

```<code>public class Splitter<InputType, OutputType> implements Pluggable<?, InputType> {
    public void consume(Pluggable<?, InputType> previous) {
        // retrieves for example a list of InputType objects
    }

    public Collection<OutputType> produce() {
        // filters the collection it got and returns a sublist for example
    }
}
</code>```

In the end, the components might look something like this:

Reader<File, Foo> --> Splitter<Foo, Foo> --> Model<Foo, Void> --> Test<Model, Bar> --> Writer<Bar, DAO>

I don't know how else to describe the problem I'm having, but I'm sure something like this is quite achieveable. For visual example, here's the image of RapidMiner's process

Note that I'm not trying to replicate or copy Rapid Miner, it's just that the project I was assigned looks like it can be implemented in simiar way.

I'd appreciate any help regarding how to design such application.

答:
I know it's an oldish question, but check out ReactiveX if you haven't already. I discovered it recently, and it's really changed how I see designs like these. It's basically a combination of type-safe observables, event-based push (sync or async), and classic pipes-and-filters.

http://reactivex.io/

You just write little components and snap them together into pipelines, like lego for plumbers.


答:
It is perfectly fine, as long as the class hierarchy on which you are doing this is small, self-contained, and not liable to be extended by someone who is not at liberty to refactor it.

The visitor pattern is not a bad idea, but it is a hassle to implement, and more importantly, every time you try to read it, you are forced to read a lot of code. Compare this to the simplicity, straightforwardness, and all-in-one-place neatness of switching on an enum, or calling "is_xyz()" methods on the base class.

You employ a pattern of this kind for convenience, not for keeping the purists happy.

There was a similar question here: Is it okay to have objects that cast themselves, even if it pollutes the API of their subclasses? about a similar mechanism, and my answer there suggesting that doing this is fine got a score of -5, (5 upvotes and 10 downvotes,) so it appears that the number of people who would disagree with me is twice the number of people who would agree.  Nonetheless, I stand by my statement. I have not 3, not 5, not 10, but 30 years of uninterrupted full-time programming experience, and this is my opinion, for what it's worth.


问:
Using Websocket for a multiple-page website
Is using Websocket (in particular, in a Java, SpringMVC webapp, with the Spring Websocket support libs, but the question probably applies to any language) for a multiple-page website a bad idea ?

I'm currently developing a website that reloads the entire page most of the times during user navigation. One of the requirements is to have a live notifications system.

I know that Websocket is an excellent choice for live events, however I'm not sure if it is only supposed to be used on one-page webapps. I suppose that since my users will navigate between pages, the websocket handshake will have to be remade after each request, which might be bad because of the additional overhead (not so sure though..).
However some users might stay on the same page for long periods of time - and I need to be sure that they get notifications right on time - and would prefer to avoid older polling techniques.

Should I totally forget about using Websocket, or is it totally okay to use it on single-page as well as multiple-pages websites ?

Thanks ! :)

答:
I suppose that since my users will navigate between pages, the websocket handshake will have to be remade after each request, which might be bad because of the additional overhead (not so sure though..).

Bad in what sense? Yes, there will be additional load on your server, but it probably won't be a big deal. Your main goal at this stage should be to get it running and have an architecture that is parallelizable to multiple servers. That way, should your site become really popular, you can spend your way out of inefficiencies temporarily until you can make your site more efficient.

What's really inefficient is optimizing the heck out of your site before you know you have a target market.


问:
Spartan programming... What is it good for?
We are being forced to use Spartan programming on a project, to everybody's dismay. So I get it, it makes the methods really short and it handles the simple cases first. But is it really worth the price of the code looking like something out of the Obfuscated C Code contest? </p>

<p>Can you see it being useful for something? </p>

答:
Here's an article that discusses the benefits of spartan programming

http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/SendAnEmail_case_study

ContentLicense: CC BY-SA 2.5


问:
Conceptual mismatch between DDD Application Services and REST API
I'm trying to design an application that has a complex business domain and a requirement to support a REST API (not strictly REST, but resource-oriented). I have some trouble coming up with a way to expose domain model in a resource-oriented manner.

In DDD, clients of a domain model need to go through procedural 'Application Services' layer to access any business functionality, implemented by Entities and Domain Services.
For example there's an application service with two methods to update a User entity:

```<code>userService.ChangeName(name);
userService.ChangeEmail(email);
</code>```

The API of this Application Service exposes commands (verbs, procedures), not state.

But if we also need to provide a RESTful API for the same application, then there is a User resource model, that looks like this:

```<code>{
name:"name",
email:"email@mail.com"
}
</code>```

The resource-oriented API exposes state, not commands. This raises the following concerns:

each update operation against a REST API can map to one or more Application Service procedure call, depending on what properties are being updated on the resource model

each update operation looks like atomic to REST API client, but it is not implemented like that. Each Application Service call is designed as a separate transaction. Updating one field on a resource model could change validation rules for other fields. So we need to validate all resource model fields together to ensure that all potential Application Service calls are valid before we start making them. Validating a set of commands at once is much less trivial that doing one at a time. How do we do that on a client that doesn't even know individual commands exist?

calling Application Service methods in different order might have a different effect, while REST API makes it look like there's no difference (within one resource)

I could come up with more similar issues, but basically they all are caused by the same thing. After each call to an Application Service, state of the system changes. Rules of what is valid change, the set of actions an entity can perform next change. A resource-oriented API tries to makes it all look like an atomic operation. But the complexity of crossing this gap must go somewhere, and it seems huge.

In addition, if the UI is more command-oriented, which often is the case, then we'll have to map between commands and resources on the client side and then back on the API side.

Questions:

Should all this complexity just be handled by a (thick) REST-to-AppService mapping layer?

Or am I missing something in my understanding of DDD/REST?

Could REST simply be not practical for exposing functionality of domain models over a certain (fairly low) degree of complexity?

答:
The key issue here is, how is business logic invoked transparently when a REST call is made? This is a problem that is not directly addressed by REST.

I have solved this by creating my own data management layer over a persistence provider such as JPA. Using a meta model with custom annotations, we can invoke the appropriate business logic when the entity state changes. This ensures that irrespective of how the entity state changes the business logic is invoked. It keeps your architecture DRY and also your business logic in one place.

Using the above example, we can invoke a business logic method called validateName when the name field is changed using REST:

```<code>class User {
      String name;
      String email;

      /**
       * This method will be transparently invoked when the value of name is changed
       * by REST.
       * The XorUpdate annotation becomes effective for PUT/POST actions
       */
      @XorPostChange
      public void validateName() {
        if(name == null) {
          throw new IllegalStateException("Name cannot be set as null");
        }
      }
    }
</code>```

With such a tool at your disposal, all you will need to do is annotate your business logic methods appropriately.

Body:
The key issue here is, how is business logic invoked transparently when a REST call is made? This is a problem that is not directly addressed by REST.

I have solved this by creating my own data management layer over a persistence provider such as JPA. Using a meta model with custom annotations, we can invoke the appropriate business logic when the entity state changes. This ensures that irrespective of how the entity state changes the business logic is invoked. It keeps your architecture DRY and also your business logic in one place.

Using the above example, we can invoke a business logic method called validateName when the name field is changed using REST:

class User {
      String name;
      String email;

      /**
       * This method will be transparently invoked when the value of name is changed
       * by REST.
       * The XorUpdate annotation becomes effective for PUT/POST actions
       */
      @XorPostChange
      public void validateName() {
        if(name == null) {
          throw new IllegalStateException("Name cannot be set as null");
        }
      }
    }

With such a tool at your disposal, all you will need to do is annotate your business logic methods appropriately.


问:
What's the best practise for storing web server credentials for your web app deployment?
I was looking at the Oracle documentation for the weblogic maven plugin.

In it, they store the weblogic user name and password for accessing in the pom.xml.

Just wondering, isn't this a terrible idea? How should one handle this?

```<code> <plugin>
      <groupId>com.oracle.weblogic</groupId>
      <artifactId>weblogic-maven-plugin</artifactId>
      <version>10.3.4</version>
      <configuration>
          <adminurl>t3://localhost:7001</adminurl>
          <user>weblogic</user>
          <password>weblogic123</password>
          <upload>true</upload>
          <action>deploy</action>
          <remote>false</remote>
          <verbose>true</verbose>
<source>${project.build.directory}/${project.build.finalName}.${project.packaging}</source>
         <name>${project.build.finalName}</name>
      </configuration>

      <executions>
         <execution>
            <phase>install</phase>
              <goals>
                <goal>deploy</goal>
              </goals>
         </execution>
       </executions>

  </plugin>
</code>```

答:
This is a terrible idea if there are no clear warnings on the example page. It encourages developers to put their secrets in their configuration files on their developer machines. Those files end up in version control, which is very, very wrong.

The only location where configuration files might have secrets (see below about what I mean by secrets) is on strictly controlled production servers which can be accessed by trusted system administrators only. On developer machine, the same file may be presented as a template:

<configuration>
    <adminurl>{{ADMIN_URL}}</adminurl>
    <user>{{ADMIN_USER}}</user>
    <password>{{ADMIN_PASSWORD}}</password>
    <upload>true</upload>
    <action>deploy</action>
    ...
</configuration>
```

where the placeholders will be replaced by the actual values during the deployment (and can be replaced by different values during the local debugging).

The secrets themselves may be stored:

In a separate version control,

Which is encrypted,

Which can be accessed only by the process which pushes the new revisions to production, as well as by the same system administrators who have a complete access to the servers anyway.

When deploying the revisions to production, a better option than using a template is to put secrets in a completely separate file. This file may be encrypted (with only the process¹ running the app being able to decrypt it), which means that developers may access the actual configuration (and see the value of the actual adminurl and user elements) for debugging purposes, without being able to access the secret itself.

Secrets can also be stored in a database. The benefits, compared to a simple file, are:

The audit capability, that is the ability to track who accessed which secrets when.

The fact that all the secrets are stored in the same central location, which makes it simple to manage security, to revoke permissions, to reset compromised secrets, etc.

The drawbacks are:

The additional complexity, which may be too overwhelming for a small application (given that you need to deploy a separate virtual machine for the database, ensure it is protected, ensure logs and audit from this machine are sent to central logs server which is protected as well, etc.)

The fact that all the secrets are stored in the same central location, which makes it a perfect target for an attacker (including a disgruntled employee.)

Note that:

When I talk about secrets, I mean things like secret keys for the APIs. The passwords of the actual users should never ever be stored: the only thing which can be stored is a salted hash, never the plain password itself (nor the encrypted version of it). The term "password" used in the example is very misleading.

weblogic is a terrible user name. Jeff Brown is a user. Cindy Coleman is a user. admin or web or accounting are not users, because they don't correspond to a single person. Such names encourage sharing the credentials among several persons (giving root password to all developers, including freelancers and interns, or accounting password to 5 accountants of the company, including the one who will be fired the next week), which is a terrible idea.

Password weblogic123 for the user weblogic sucks. Even as an example. The password {b>\27P1.TrFM2WU@I5dc| is a much better example.

¹ In Windows, this is possible by specifying the encryption property of the file: the decryption is done transparently for the application, so that the app doesn't have to deal with encryption keys (and the storage of the encryption keys). The same should be possible in other operating systems as well.

Body:
This is a terrible idea if there are no clear warnings on the example page. It encourages developers to put their secrets in their configuration files on their developer machines. Those files end up in version control, which is very, very wrong.

The only location where configuration files might have secrets (see below about what I mean by secrets) is on strictly controlled production servers which can be accessed by trusted system administrators only. On developer machine, the same file may be presented as a template:

<configuration>
    <adminurl>{{ADMIN_URL}}</adminurl>
    <user>{{ADMIN_USER}}</user>
    <password>{{ADMIN_PASSWORD}}</password>
    <upload>true</upload>
    <action>deploy</action>
    ...
</configuration>

where the placeholders will be replaced by the actual values during the deployment (and can be replaced by different values during the local debugging).

The secrets themselves may be stored:

In a separate version control,

Which is encrypted,

Which can be accessed only by the process which pushes the new revisions to production, as well as by the same system administrators who have a complete access to the servers anyway.

When deploying the revisions to production, a better option than using a template is to put secrets in a completely separate file. This file may be encrypted (with only the process¹ running the app being able to decrypt it), which means that developers may access the actual configuration (and see the value of the actual adminurl and user elements) for debugging purposes, without being able to access the secret itself.

Secrets can also be stored in a database. The benefits, compared to a simple file, are:

The audit capability, that is the ability to track who accessed which secrets when.

The fact that all the secrets are stored in the same central location, which makes it simple to manage security, to revoke permissions, to reset compromised secrets, etc.

The drawbacks are:

The additional complexity, which may be too overwhelming for a small application (given that you need to deploy a separate virtual machine for the database, ensure it is protected, ensure logs and audit from this machine are sent to central logs server which is protected as well, etc.)

The fact that all the secrets are stored in the same central location, which makes it a perfect target for an attacker (including a disgruntled employee.)

Note that:

When I talk about secrets, I mean things like secret keys for the APIs. The passwords of the actual users should never ever be stored: the only thing which can be stored is a salted hash, never the plain password itself (nor the encrypted version of it). The term "password" used in the example is very misleading.

weblogic is a terrible user name. Jeff Brown is a user. Cindy Coleman is a user. admin or web or accounting are not users, because they don't correspond to a single person. Such names encourage sharing the credentials among several persons (giving root password to all developers, including freelancers and interns, or accounting password to 5 accountants of the company, including the one who will be fired the next week), which is a terrible idea.

Password weblogic123 for the user weblogic sucks. Even as an example. The password {b>\27P1.TrFM2WU@I5dc| is a much better example.

¹ In Windows, this is possible by specifying the encryption property of the file: the decryption is done transparently for the application, so that the app doesn't have to deal with encryption keys (and the storage of the encryption keys). The same should be possible in other operating systems as well.


答:
I would only recommend implicit conversions between types that roughly represent the same values in different ways. For instance:

Different color types like RGB, HSL, HSV and CMYK.

Different units for the same physical quantity (Meter vs Inch).

Different coordinate systems (polar vs Cartesian).

However, there are some strong guidelines that indicate when it is not appropriate to define an implicit conversion:

If the conversion causes a significant loss of precision or range, then it shouldn't be implicit (e.g.: from float64 to float32 or from long to int).

If the conversion can throw an (InvalidCast) exception, then it shouldn't be implicit.

If the conversion causes a heap allocation each time it is performed, then it shouldn't be implicit.

If the conversion is not an O(1) operation, then it shouldn't be implicit.

If the source type or the target type is mutable, then the conversion shouldn't be implicit.

If the conversion is dependent on some sort of context (database, culture settings, configuration, file system, etc.) then it shouldn't be implicit (I would also discourage an explicit conversion operator in this case).

Now say your conversion operator f: T1 -> T2 doesn't violate any of the rules above, then the following behavior strongly indicates that the conversion can be implicit:

If a == b then f(a) == f(b).

If a != b then f(a) != f(b).

If a.ToString() == b.ToString() then f(a).ToString() == f(b).ToString().

Etc. for other operations that are defined on both T1 and T2.

Title: When should I use C#'s implicit type conversion operator?

Body:
In C#, we can overload the implicit conversion operator like this (example from MSDN):

```<code>struct Digit
{
    /* ... */
    public static implicit operator byte(Digit d)  // implicit digit to byte conversion operator
    {
        /* ... */
    }
}
</code>```

Thus, we can have a type, a custom value type, magically converting itself to another (unrelated) type, leaving the audience in bewilderment (until they peer into the backstage and see the implicit conversion operator, that is).

I don't like leaving anyone who reads my code in bewilderment. I don't think many people do.

The question is, what are the use-cases of the implicit type conversion operator which won't render my code much more difficult to understand?


问:
How do I communicate to a colleague that their code does nothing?
Stay with me here. When I say the code "does nothing", I mean something like the following function:

void factorial(int n)
{
    int result = 1;
    for(int i = 1; i <= n; ++i)
    {
        result *= i;
    }
}
```

Sure, this function creates a local variable and computes a value, but it doesn't do anything to advance the program; there is no way to make use of the result of the computation, and it has no side-effects.

Keep in mind that this is a contrived example for the purposes of the question, but the code I refer to may be more complicated.

When I encounter such code, I often spend some extra time and go through it several times, because I worry that I might be missing something. I could just take the high road, or fix the bug and be done with it, but I worry that this slowdown would reflect badly on me and my performance.

So, should I take the high road, and assume the team understands, or should I communicate that the code doesn't do much? If the latter is the better option, how do I do that without being condescending or disrespectful?

答:
If this code is presented during code review, it seems you have little problem; just provide feedback that you are not clear what it does and ask for a unit test.

If it's not during code review, then you might want to think not just about how to rectify the immediate issue, but look for a deeper solution in terms of process change.

Any of the following might pick this up:

Suitable warning levels at compile time, coupled with a zero warning requirement on code.

A code review process

Sufficient unit testing coverage.

Commenting standards

Now, the sheer fact that you have this problem suggests to me that maybe some of your team members are not great at reading code. Unfortunate, but in the real world so very common.

I'd note that above practices are useful in even a very strong team (commenting is debatable).

However, the useful thing about the above practices that are particularly useful in a weaker team; they provide a framework to help improve code quality without it getting personal.


问:
Skillset improvement in coming new year
Here is a little background information.

I have been working for Java 10 years.

The product I am working on went to live about 3 years ago. Now, the product is getting stable.

After all the post-product drama, I gained a lot of knowledge about Oracle & SQL.
People(mainly management) were desperated enough to give me deep oracle-related task over DBAs. I admit I considered becoming DBA but eventually decided to remain as a programmer.

DBAs & Management are demanding all the DB & Query related task back to DBA, which makes me a bit sad.

In short, I anticipate a lot of time next year.
What would you do to improve your skillset??

I am thinking to upgrade my Java version(Not from experience though, we are using JDK1.5) to 1.6 getting certificate.

Any good idea from fellow developers??

-----------Edit ---------------------

How about data modeling for application? Do you guys think it is developer role??

答:
This is something that I am copying from StackOverflow.

Being a programmer with that kind of experience, and wanting to learn things that take you into a new level, I strongly suggest that you study non-programming subjects that can make you a better programmer.

These are some subjects that I have studied and found extremely useful:

Cognitive psychology. It explains how people perceive and communicate information; it's the basis of conceptual modelling.

Organisational theory. It provides a good framework to understand the context where most information systems work.

Management "science" and people skills. It can give you clues about the social factors and motivations that interact with software systems.

Linguistics. Natural languages may be formal systems, after all, and thinking in terms of lexicon, syntax and semantics is always useful for software people.

Architecture (the one making houses and buildings, not software). Its abstract nature and the use of patterns make it a great exercise for the mind.

In general, anything involving formalisms would do you good. Anything that involves people plus information together is also very useful. I think that spending time learning these things will differentiate you from other people of your same age/experience.

Hope this helps.

Title: Skillset improvement in coming new year


答:
The short answer is, of course, whether you want to break with naming conventions for what are essentially constants... Quoting from the JLS:

Constant Names

The names of constants in interface types should be, and final variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore "_" characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech.

The long answer, with regards to use of toString(), is that's definitely the method to override if you want a more readable representation of the enum values. Quoting from Object.toString() (emphasis mine):

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

Now, I'm not sure why some of the answers drifted to talking about converting enums to-and-fro with String values, but I'll just give my take here as well. Such serialization of enum values can easily be taken care of by using either the name() or ordinal() methods. Both are final and thus you can be sure of the returned values so long as the names or positioning of the values do not change. To me, that's a clear-enough marker.

What I gather from the above is: today, you might want to describe YELLOW as simply "yellow". Tomorrow, you might want to describe it as "Pantone Minion Yellow". These descriptions should be returned from calling toString(), and I wouldn't expect either name() or ordinal() to change. If I do, that's something I need to resolve within my codebase or my team, and becomes a greater question than just an enum naming style.

In conclusion, if all you intend to do is to log a more readable representation of your enum values, I'll still suggest sticking to conventions and then overriding toString(). If you also intend to serialize them into a data file, or to other non-Java destinations, you still have the name() and ordinal() methods to back you up, so there's no need to fret over overriding toString().

ContentLicense: CC BY-SA 4.0


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
It really depends what you are looking for, as an organisation that does a lot of dynamic web work involving images, I tend to like to ask a geometry question pertinent to the job.  In any case, I tend to ask a geometry question, as I find it a good maths test that is nice and visual and can show a candidates ability to visually present their working and methodically work through a problem.

For advanced candidates, I occasionally give the following question:

This image shows a crescent moon.  The width of the crescent from B to D
  is 9cm and between E and F, 5cm. C is
  the centre of the larger circle.

a) Please calculate the area of the crescent.

b) Describe the calculations necessary to resize an image to fit in to the inner circle from any given size, and position it within the circle if the centre point is known.

For an easier question I usually give the same sort of question, but use the "square within a circle within a square" example.  Though this is very easy, so I would expect perfect algebra on it.

Over and above that, I tend to ask them to knock up an algorithm for generating all combinations of a variable length data set.


问:
How to design a serverside heartbeat with nodejs?
I would post this on https://stackoverflow.com/, but figured I am not looking for code, just an idea how to accomplish this.

I have a gameserver that interacts with nodejs and uses the websocket module. It works great, there is one problem:

When a user is joining a game and the map gets loaded, a user could easily press F12, go into Chrome dev tools and remove the overflow:hidden css attribute, thus.. revealing the rest of the map. (A Web-based map hack!). My map dimensions are 3000x3000 + in size.

I need some type of way to to send something to nodejs every xx seconds and then nodejs needs to send back a token with that request as well to keep that css attribute at overflow:hidden and if the data being sent is manipulated in anyway, I can then shut down that player's connection.

Doing this method, I would use the setInterval with Javascript to create the heartbeat. Am I going about this the right way?

Edit: And yes, this will require more bandwidth, but well worth it imo.

答:
You'd be better off using that extra bandwidth to spoon feed the map to the users as they discover it.

As you've noticed, anything client side can be easily hacked.  You might think of a fancy way to encrypt the data, but you'd still have to send the decrypt keys to the browser.

For that matter, you don't really know if you're talking to a browser at all - you're just sending data over a TCP port to a computer that kind of maybe sort of looks like it might be a common web browser.


问:
Is FormsAuthentication obsolete?
I am creating a website using ASP.NET MVC 5. Has Microsoft release any technology to replace FormsAuthentication or do they still recommended  authenticating the user using FormsAuthentication for MVC 5?

UPDATE Jan 2020:

It's been almost 5 five years since I asked this question, the web development world has drastically changed. Now I am convinced that FormsAuthentication IS obsolete.

Please consider token based auth when implementing user authentication in ASP.NET based web apps.

答:
Yes. FormsAuthentication is deprecated in MVC 5 and onwards.

At least, that's the short answer.

The long answer is that pre-MVC 5 traditional FormsAuthentication is still ok to use. It is, however being phased out in favour of alternative approaches such as ASP.NET Identity.

In Visual Studio 2013, the authentication options supplied for and MVC 5 application are as follows:

In this case, Individual User Accounts is referring to ASP.NET Identity.

According to Microsoft, the former ASP.NET Membership has been replaced with ASP.NET Identity,

[ ... ] the sample application will be configured to use ASP.NET Identity (formerly known as ASP.NET membership)

(Emphasis mine)

Microsoft also state

The new membership system is based on OWIN rather than the ASP.NET Forms Authentication module.

So Identity didn't exactly replace FormsAuthentication, but rather it replaced the Membership system  which used FormsAuthentication. A good thing too, because according to a question I asked in 2013, Membership is rather confusing.

A type of FormsAuthentication still exists though. According to Microsoft,

ASP.NET also has a forms authentication support through the FormsAuthenticationModule, which, however, can only support applications hosted on ASP.NET and doesn't have claim support. Here is a rough feature comparison list:

So if you'd still like to use FormsAuthentication, check out Understanding OWIN Forms authentication in MVC 5.

So Microsoft encourages you to use ASP.NET Identity. You don't have to, of course. You can simply select No Authentication and the project will not implement anything for you. It is then up to you to fulfil your membership/login needs.

Title: Is FormsAuthentication obsolete?


问:
which one is recommended object-oriented design?
I made simple object-oriented prgram, and think about design.
I wonder which one of belows is recommended object-oriented design.

Most left side class is "Main" class. Black arrow means they are "Has a" relations. Blue arrows are inheritance. Red arrows mean it create pointed class as a object and call the method of it. Thanks.

答:
"Red arrows mean it create pointed class as a object and call the method of it."

So you did not separate creation from usage?

This is pretty much opinionated, but one "recommended" way of creating OO programs, especially when multiple classes are involved, is to make use of dependency injection. One central aspect of DI is: if one object needs another object, it does not create it directly, but it gets the object "injected" from outside (the rationale behind is that it will allow you to write unit tests by injecting mocks instead of the "real" objects).

So if you implement DI "manually", without a "generic DI container component", and without any additional factory classes, this means, outside of your test code, there must be a central place, often just the "main" program, where all the objects are created and "assembled together". This leads straight forward to a creation graph which looks like your first picture.

Nevertheless the gist of object orientation is that you have a usage graph like the second one - objects which are related communicate directly to each other through some defined interfaces, and you try to keep dependencies as local as possible. The intention behind this is to keep the impact of later changes low.

For small programs the effort of introducing DI may not be worth the hassle, so following another "recommended way" - the YAGNI principle - might be the better way to go, and having a creation graph like the second one can be fine, even for a lot of real world scenarios. Moreover, real world scenarios will typically use a mixed approach. For example, if some of your classes represent pure data objects, without any business logic, there is no much benefit to "mock them out", so creating those objects directly where they are needed may be perfectly ok, whilst for other classes you may choose to apply DI.


问:
how can the presenter or view interact with the model in the MVP pattern?
I'm learning the MV* patterns. MVP in this case. I'm trying to refactor an old android application into the MVP pattern to make things less tightly coupled, but I'm struggling one one concept. I know that the presenter get's data from the domain layer which connects through the data layer, but how can the view communicate with the data, directly or indirectly? here's an example of what I'm trying to figure out:

I've got a long running download service (I assume this should be in the data layer) that needs to be started or stopped depending on user interaction in the UI. How would I communicate those signals to the service in the data layer? should I do that through the domain layer?

from what I've seen it looks like the UI can not talk back to the data or domain layers.

If someone would be willing to explain this to me I'd be very grateful.

here are some of the articles I'm working off of:
first resource |
second resource |
third resource

答:
In the MVP pattern is the View is "dumb".  It doesn't really do anything.  The presenter acts as the controlling object in the heirarchy, while the Model stores the data and has business logic methods on it.

That doesn't preclude the View from firing events, which are hooked by the Presenter to methods or properties on the model, or to other testable logic on the Presenter itself.

Your presenter has access to both the model and the view.  On your presenter you can therefore hook up events fired on the View to methods or properties on the Model.  The view and the model never know anything about each other.


问:
Persist data downloaded by Celery workers
I'm working in a tool that downloads tweets from Twitter to process them later. For this purpose I'm using Celery with RabbitMQ, sending task with the keywords that must be tracked by the workers.

My problem now is that I must pre-process the tweets downloaded by a worker in a second task so I should merge both tasks to have access to them or persist all tweets in a common storage and fetch them in the new task. Regarding the chosen option I need to persist all tweets for the final processing.

So here is the question. What is the best way to merge and persist all the tweets downloaded by the workers to have access to the whole dataset?

答:
We are using something very similar to this. Can't you add a task that saves the data once it has completed processing them? We use Kombu to download (Consumer) and to Publish (Producer) back to RMQ and celery only has a very specific task which sort of is your case.

RMQ queue A gets consumed by Consumer

Message obtained by Consumer gets sent to Celery for processing

Message returned by Celery is passed to Publisher with results obtained and posted to RMQ queue B.

Hope it helps.


问:
Making API calls with celery
I'm designing a system for a client where the requirements are:

they upload a JSON file (one object/line)

make a call to an API with the JSON object as the payload

record the state (success/failure) of each API call in a database

make one retry if there's a failure.

I decided to build it out using celery and a sqlite database as the backend. The number of JSON lines is not large — perhaps a couple million at most — which will fit in memory. I have all the individual components working fine (can upload file, can read file, can call API, can write to db, etc.), but I am not sure about the overall architecture of dispatching tasks using celery.

Assuming there are N lines in the file, should I:

Option A:

Create N objects in the database with a result column (initially null).

Create N celery tasks and pass the object id as the parameter and the payload

Make the subtask call the API and update the object's result field to success/failure.

Let celery's retry feature attempt to call the API again in case of failure.

Option B:

Create N objects in the database with a result column (initially null).

Create 1 celery task and pass the entire list of N object ids and N payloads

Loop through all N objects and update the database with the result at each step.

When the previous task finishes, it fires another one-time celery task that reads the database for all objects with failure result and retries them.

I'm favoring option A because of its simplicity but I don't know what the limits are on the number of celery tasks that can be scheduled and if the broker (RabbitMQ) will handle it. With option B, the big risk is that if the celery task were to get terminated for any reason at some line M, then all following objects will never be tried.

Any thoughts on these two or if there's a third better alternative?

答:
Option A sounds like the way to go as you can set workers it the API independently instead of a huge tasks that only a single worker can manage.

I have a very similar scenario using kombu and Celery:

We get a message posted to RMQ by some integration to a RMQ queue

We have a kombu consumer draining events

When event is received we execute the callback (post to local python queue)

celery gets the message sent over the python queue and process it

Once finished it returns the results and we relay the message to a kombu producer

The producer posts back to RMQ

As you can see, we use basically the same approach as you. We have this in production handling around 2000 messages per hour with no problem.

Title: Making API calls with celery


答:
This is issue of following the Law of Demeter. In first case, the Main class knows about all the other classes. If it has dependency on all of those classes, then you have to check if Main works properly if you change any of those classes + the one that is using it. If you needed to mock dependencies of Main class, then you would have to mock all of those dependencies.

In the second case, that is not a problem, assuming those dependencies are encapsulated and not accessible transitively. Each of the classes has only one dependency, making them easier to test and reason about.

If you can access all of the classes transitively (eg. Main.A.B.C), then there is not much difference between first and second case and I would really question your whole design.

Title: which one is recommended object-oriented design?

Body:
I made simple object-oriented prgram, and think about design.
I wonder which one of belows is recommended object-oriented design.

Most left side class is "Main" class. Black arrow means they are "Has a" relations. Blue arrows are inheritance. Red arrows mean it create pointed class as a object and call the method of it. Thanks.


问:
Deciding factors in pair programming
Are there specific things that you look out for before getting the team into pair programming? Obviously pairing someone who's great with C++ with another who knows ASP.NET best won't get me far, but how about someone who's great with C++ with another who knows Java best but can pick up C++ quick enough? </p>

<p>What else? Experience levels? Character traits? </p>

答: There is a book called Pair programming illuminated (ISBN 9780201745764) which describes several aspects of pair programming, among other things teaming up persons with different experience. One of the chapters is named "My Partner Is a Total Loser" and Other Excess Ego Problems.

Title: Deciding factors in pair programming


问:
Big O equivalence for LINQ select
I'm trying to determine if there is a change in the Big O equivalence of a nested loop when I use a LINQ select instead.

```<code>public void myFunc(List<Foo> fooList, List<Bar> barList)
{
    foreach(Foo foo in fooList)
    {
        foreach(Bar bar in barList)
        {
            if(foo.PropA == bar.PropA && bar.PropZ.HasValue)
                foo.PropC = foo.PropB * bar.PropZ;
        }
    }
}
</code>```

I believe this nested loop example is O(n^2) for complexity.

I replaced the nested loop with a LINQ select like this:

```<code>public void myFunc(List<Foo> fooList, List<Bar> barList)
{
    foreach(Foo foo in fooList)
    {
        Bar bar = (from b in barList
                    where foo.PropA == b.PropA
                    select b).FirstOrDefault();

        if(bar.PropZ.HasValue)
            foo.PropC = foo.PropB * bar.PropZ;
    }
}
</code>```

If nothing else, the code appears to be a little cleaner to read as it explicitly states "we're looking for this particular Bar to work with."

My question is this: Does using the LINQ select reduce the Big O complexity?

答:
No difference in complexity, both are O(n²) because Linq's Where is O(n).

The use of FirstOrDefault is equivalent to do this :

```<code>if(foo.PropA == bar.PropA && bar.PropZ.HasValue)
{
    foo.PropC = foo.PropB * bar.PropZ;
    break;
}
</code>```

This is an improvement on the calculation time, but not on the complexity.

You can do better by using an Hashmap for one of the two list's.

The Linq's Join operator will create a Hashmap for one of the 2 lists, so you will gain on performance when searching two matching element :

```<code>    public void myFunc(List<Foo> fooList, List<Bar> barList)
    {
        var rows = fooList.Join(
                        barList,
                        f => f.PropA,
                        b => b.PropA,
                        (f, b) => new { Foo = f, Bar = b }
                   );

        foreach (var row in rows)
        {
            if (row.Bar.PropZ.HasValue)
                row.Foo.PropC = row.Foo.PropB * row.Bar.PropZ.Value;
        }
    }
</code>```

This should run in O(n log(n))

Title: Big O equivalence for LINQ select

Body:
No difference in complexity, both are O(n²) because Linq's Where is O(n).

The use of FirstOrDefault is equivalent to do this :

if(foo.PropA == bar.PropA && bar.PropZ.HasValue)
{
    foo.PropC = foo.PropB * bar.PropZ;
    break;
}

This is an improvement on the calculation time, but not on the complexity.

You can do better by using an Hashmap for one of the two list's.

The Linq's Join operator will create a Hashmap for one of the 2 lists, so you will gain on performance when searching two matching element :

    public void myFunc(List<Foo> fooList, List<Bar> barList)
    {
        var rows = fooList.Join(
                        barList,
                        f => f.PropA,
                        b => b.PropA,
                        (f, b) => new { Foo = f, Bar = b }
                   );

        foreach (var row in rows)
        {
            if (row.Bar.PropZ.HasValue)
                row.Foo.PropC = row.Foo.PropB * row.Bar.PropZ.Value;
        }
    }

This should run in O(n log(n))


问:
C++ strongly typed typedef
I've been trying to think of a way of declaring strongly typed typedefs, to catch a certain class of bugs in the compilation stage. It's often the case that I'll typedef an int into several types of ids, or a vector to position or velocity:

```<code>typedef int EntityID;
typedef int ModelID;
typedef Vector3 Position;
typedef Vector3 Velocity;
</code>```

This can make the intent of code more clear, but after a long night of coding one might make silly mistakes like comparing different kinds of ids, or adding a position to a velocity perhaps.

```<code>EntityID eID;
ModelID mID;

if ( eID == mID ) // <- Compiler sees nothing wrong
{ /*bug*/ }

Position p;
Velocity v;

Position newP = p + v; // bug, meant p + v*s but compiler sees nothing wrong
</code>```

Unfortunately, suggestions I've found for strongly typed typedefs include using boost, which at least for me isn't a possibility (I do have c++11 at least). So after a bit of thinking, I came upon this idea, and wanted to run it by someone.

First, you declare the base type as a template. The template parameter isn't used for anything in the definition, however:

```<code>template < typename T >
class IDType
{
    unsigned int m_id;

    public:
        IDType( unsigned int const& i_id ): m_id {i_id} {};
        friend bool operator==<T>( IDType<T> const& i_lhs, IDType<T> const& i_rhs );
};
</code>```

Friend functions actually need to be forward declared before the class definition, which  requires a forward declaration of the template class.

We then define all the members for the base type, just remembering that it's a template class.

Finally, when we want to use it, we typedef it as:

```<code>class EntityT;
typedef IDType<EntityT> EntityID;
class ModelT;
typedef IDType<ModelT> ModelID;
</code>```

The types are now entirely separate. Functions that take an EntityID will throw a compiler error if you try to feed them a ModelID instead, for example. Aside from having to declare the base types as templates, with the issues that entails, it's also fairly compact.

I was hoping anyone had comments or critiques about this idea?

One issue that came to mind while writing this, in the case of positions and velocities for example, would be that I can't convert between types as freely as before. Where before multiplying a vector by a scalar would give another vector, so I could do:

```<code>typedef float Time;
typedef Vector3 Position;
typedef Vector3 Velocity;

Time t = 1.0f;
Position p = { 0.0f };
Velocity v = { 1.0f, 0.0f, 0.0f };

Position newP = p + v*t;
</code>```

With my strongly typed typedef I'd have to tell the compiler that multypling a Velocity by a Time results in a Position.

```<code>class TimeT;
typedef Float<TimeT> Time;
class PositionT;
typedef Vector3<PositionT> Position;
class VelocityT;
typedef Vector3<VelocityT> Velocity;

Time t = 1.0f;
Position p = { 0.0f };
Velocity v = { 1.0f, 0.0f, 0.0f };

Position newP = p + v*t; // Compiler error
</code>```

To solve this, I think I'd have to specialize every conversion explicitly, which can be kind of a bother. On the other hand, this limitation can help prevent other kinds of errors (say, multiplying a Velocity by a Distance, perhaps, which wouldn't make sense in this domain). So I'm torn, and wondering if people have any opinions on my original issue, or my approach to solving it.

答:
I'm not sure how the following works out in production code (I'm a C++/programming beginner, like, CS101 beginner), but I cooked this up using C++'s macro sys.</p>

```<code>#define newtype(type_, type_alias) struct type_alias { \

/* make a new struct type with one value field
of a specified type (could be another struct with appropriate `=` operator*/

    type_ inner_public_field_thing; \  // the masked_value
    \
    explicit type_alias( type_ new_value ) { \  // the casting through a constructor
    // not sure how this'll work when casting non-const values
    // (like `type_alias(variable)` as opposed to `type_alias(bare_value)`
        inner_public_field_thing = new_value; } }
</code>```

OwnerDisplayName: Kian

Title: C++ strongly typed typedef

Body:
I'm not sure how the following works out in production code (I'm a C++/programming beginner, like, CS101 beginner), but I cooked this up using C++'s macro sys.

#define newtype(type_, type_alias) struct type_alias { \

/* make a new struct type with one value field
of a specified type (could be another struct with appropriate `=` operator*/

    type_ inner_public_field_thing; \  // the masked_value
    \
    explicit type_alias( type_ new_value ) { \  // the casting through a constructor
    // not sure how this'll work when casting non-const values
    // (like `type_alias(variable)` as opposed to `type_alias(bare_value)`
        inner_public_field_thing = new_value; } }


问:
How can I tactfully suggest improvements to others' badly designed code during review?
I'm a great believer in clean code and code craftsmanship, though I'm currently at a job where this isn't regarded as a top priority. I sometimes find myself in a situation where a peer's code is riddled with messy design and very little concern for future maintenance, though it's functional and contains little to no bugs.

How do you go about suggesting improvements in a code review when you believe there is so much that needs changing, and there's a deadline coming up? Keep in mind that suggesting the improvements be made after the deadline may mean they'll be de-prioritized altogether as new features and bug-fixes come in.

答:
[This answer is a little broader than the question originally posed, since  this is the redirect for so many other questions on code reviews.]

Here are some principles I find useful:

Criticize privately, praise publicly.  Let someone know about a bug in their code one-on-one.  If they did something brilliant or took on a task nobody wanted, praise them at a group meeting or in an email cc'd to the team.

Share your own mistakes.  I share the story of my disastrous first code review (received) with students and junior colleagues.  I also let students know that I caught their bug so quickly because I've made it before myself.  In a code review, this might come out as: "I think you got the index variables wrong here.  I always check that because of the time I got my indexes wrong and brought down a data center."  [Yes, this is a true story.]

Remember to make positive comments.  A brief "nice!" or "neat trick!" can make the day of a junior or insecure programmer.

Assume the other person is intelligent but sometimes careless.  Don't say: "How do you expect the caller to get the return value if you don't actually return it?!"  Say: "Looks like you forgot the return statement."  Remember that you wrote awful code in your early days.  As someone once said, "If you're not ashamed of your code from a year ago, you're not learning."

Save the sarcasm/ridicule for friends not at your workplace.   If the code is epicly awful, joke about it elsewhere.  (I find it convenient to be married to a fellow programmer.)  For example, I would not share the following cartoons (or this one) with my colleagues.