问:
Big O notation for the algorithm
What would be the big o for the algo:

```<code>for (i=0; i < n*n; i++)
  for(j=0; j<i*i; j++)
</code>```

As per my understanding

1st loop will loop upto n2 times.

2nd loop will go around n2 times.

Am I right or is it a O(n6) representation?

Also is there a easy way to say when to use log. I have assumed that whenever the loop variable is multiplied the  ln function is applied

e.g.: for (i=1; i<n*n i=i*2) Big o for the loop as per my understanding is O(ln n2) (Am I right again?)

答:
These are 2 distinct questions.

1) Yes, this is O(n^6). You can, in fact, directly compute the number of iterations, inner loop makes i^2 iterations, so sum i^2 for i from 0 to n^2. Input this into Wolfram Alpha or Matlab and you get 1/6 * n^2 * (n^2 + 1) * (2 * n^2 + 1)

2) That is a useful mnemonic. Yes, a log naturally arises when you count the number of times you need to multiply something by itself to get something else. That is not the only place it arises though. Also, O(ln(n^2)) = O(2 * ln(n)) = O(ln(n))

Title: Big O notation for the algorithm


问:
JVM memory and zero-copy (de)serialization
I am trying to understand the JVM memory model. In particular, I would like to understand whether it would be feasible to have zero-copy (de)serialization libraries, such as Cap'n Proto or FlatBuffers. In particular, these two libraries do have partial support for Java, but it is not entirely clear to me whether the implementation is zero-copy.

Let me assume that I want to deserialize something, and that this region will be read only. I will start with an array of contiguous bytes, at least from the JVM point of view, although I understand they may fail to be contiguous due to the virtual memory manager (and possibily the JVM?). This array is somewhere on the JVM heap.

What I would like to do is to produce an instance of a given class, in such a way that accessing a field of this class just means to dereference a pointer into this array, without having to copy the single parts of this array somewhere else.

Is this feasible on the JVM? If not, what would be the optimum? Can I do this with a single copy regardless of the class layout?

答:
The JVM does not mandate any specific internal representation for objects. How objects are laid out in memory is hidden and it is not possible to directly map a memory area such as an array to an object or to use pointers like in C/C++.

It is possible to  use memory-mapped files but you have to call methods which return the byte/int/double etc. located at a specific offset, so it's not as direct access as in C since it has to be routed through method calls, and you can only access primitive data types this way.

Similarily, there are libraries which try to emulate simple data structures, like the pseudo-structs in Javolution. However, this only works for simple data types again. You could try to use some tricks with JNI but at the end of the day you always end up with more indirection than in C - you can't just have a pointer to an area of memory and access it like a normal object. This is in particular because object references can't be directly serialized - taken out of the context of a concrete running instance of the JVM, they wouldn't make any sense.

Therefore if your data structure is more complex than just a set of fields of primitive data types, I think what you request is not possible on the JVM. If you are happy with just primitives, you can check out Struct class from Javolution

ContentLicense: CC BY-SA 3.0


问:
Why should your code not use 100% CPU?
I'm speaking specifically about a C# .NET 4 program running on Windows XP or higher, but general answers are also acceptable.

Assume an already optimized and efficient program. The problem here is entirely down to effects of high CPU usage on hardware, and whether a high-usage program should be throttled to reduce wear, not on whether my implementation is efficient.

A colleague today suggested that I should not aim for 100% CPU utilization on my data load processes because "modern CPUs are cheap and will degrade quickly at 100% CPU".

Is this true? And if so, why? I was previously under the impression that 100% CPU usage was preferable for an intensive or long operation, and I couldn't find any respectable sources on the subject either way.

答: To play the devil's advocate: In a way, a program that cannot reach 100% utilization could cause worse wear: Unless it is suspended waiting for a keystroke, chances are that it is suspended waiting for disk I/O most of the time. And disks are (still usually) big mechanical devices that are subject to mechanical wear or the risk of shock/gyroscopic effects when they move, not to mention power consumption.</p>

Title: Why should your code not use 100% CPU?


问:
Do objects with validation logic in their domain really represent their real world counterparts?
I asked a question about whether validation behavior should be treated the same as other types of behavior in regard to the concept of OOP being "data + behavior". I got some good answers back that addressed the question from the philosophical point of view and confirmed that the answer to that question seems to be yes.

Now I'd like to address this question from a different angle: Shouldn't objects represent their real world counterparts?

Suppose I give a paper form to someone to fill out. They can pencil in the fields on the form in any order they'd like to and they can even fill in all sorts of incorrect values. When they turn the paper in to me I, representing a broker, may hand it back to them and tell them I can't file it until they fix any invalid entries though.

There's also a comparison to be made between the format of the questions on the paper and a user interface that validates input. Maybe you put checkboxes on the paper and instruct the person to only select one. Of course software can get a lot fancier with this type of validation than a physical sheet of paper, but let's be clear that this type of validation is all in the user interface... validation in the 'domain' simply doesn't exist in the physical realm for this type of object.

Is the paper going to crumple itself up or catch on fire if you write something invalid on it?

So my question is this: if a physical piece of paper has no inherit ability to validate itself, then why would this behavior belong in the domain?

答:
If your object is "Paper", then to make it fully reusable you are right--it should be able to take any content without bursting into flame (Perhaps with some basic checks that always apply to paper, like the background color can't be black?  I mean like null checks that keep the paper object valid.)

However it is then refined into a "Form" (Let's call it a Form1040 object that extends or uses your Paper object) it many not have more intrinsic checks but it will be validated by some teller standing at a window, and if you have just scribbled randomly they may just light it on fire (although it's more likely they will just hand it back to you).  This is probably best represented as a set of validations external to the "Form1040" object that are attached to or associated with it (Think a set of numbered ruless written on the back or in a booklet named "Form1040 validations").

The nice thing about the set of validations is that you can use them to check your form before you even submit them to the teller, then the teller can use the same validations before accepting them and passing them to a data entry specialist, then the data entry process can finally apply one last check before dropping them into the database.

Trying to build the validations directly into the object is going to seriously limit reuse and maintainability. Integrating a validation mechanism specified by meta-data that works across multiple objects is a really good approach.


问:
Method Parameters Ordering
I was recently changing a method to add in an additional parameter, and I couldn't help but wonder if there were "best practices" or "generally accepted rules" in deciding what order parameters of a method should go in? Obviously, you could put it in any order you like... I'm more wondering if there are any official (or unofficial) guidelines for this. My particular language is Java but I'm thinking this could apply to any language with arguments.

Example Parameter List:

```<code>public String generateMessage(Object o, String prefix, String suffix)
    //generates a message such as: "prefix : objectName : suffix"
</code>```

I am adding a boolean, which is whether the prefix should be shown.

```<code>public String generateMessage(Object o, String prefix, boolean isPrefixVisible, String suffix)
</code>```

答:
This question is highly subjective.

In my experience, I have found that parameter lists are clear when they meet the following criteria:

The primary object upon which the method or function operates comes first. In English, a sentence might contain a noun, a verb, and another noun upon which the verb could act. E.g.: "Alice sends a message." In OO parlance, "Alice" could be the object to which the method belongs. "Sends" could be the method itself, and "a message" is its parameter: alice.sends(message). Maybe there are other parameters, but they should read roughly like a sentence: "Alice sends a message, but gives up after 30 seconds if nobody listens." alice.sends(message, 30). It is natural, our brains are already trained to think this way from an early age.

If there are more than (insert subjective number here, maybe four or five) parameters, break up the method call somehow. Maybe there is an object (e.g. builder) screaming to be refactored out. If a parameter list is long enough that you have to ask this question, it is already long enough to be difficult to understand.

Title: Method Parameters Ordering


问:
Extension in use case diagram: Library management example?
I have problem to understand the extension relation in the use case diagrams, sometimes some relations seem extension.

For example in the library system, what is the relation between borrowing a book use case and reservation a book use case?

Could the reservation be the extend of borrow?

Scenario of Reserve a book:

Member refers to the librarian

Gives the information of the book

Librarian record the book in the reservation list  for the member

Scenario of Borrow a book:

Member refers to the librarian

Gives the information of the book

Librarian lend the book if it's available

Librarian reserve the book for the member if it's not available

In general what are rules of thumb to find out extension relation?

答:
I say you shouldn't bother trying to figure out if you should use extends/includes. That only causes you to lose the focus of what you are really trying to accomplish, which is describe what your system has to be able to do. They have their "rare" beneficial uses but that's the exception. You certainly don't need them for each trivial "common" step.

I used to mull over those details until I realized "in hindsight" that they don't really add much value to the overall process and focusing on them ends up pushing you towards implementation details that you really shouldn't be concerned with at the use-case level.  For example, while it may be that your design will reserve a book the same way no matter how you got there, once you start design you very well may discover that it can't be done the same way. Now, you've got to "un-extend" the use-case because you made a design decision at the requirements level.

When it is appropriate to use extends/includes YOU WILL KNOW, you won't have to ask yourself should I use it or not.

To directly answer your question "what are the rules": If it isn't clear-cut then don't bother.

Also, just as an FYI, steps 1 and 2 should simply be "Member requests to Reserve Book"/"Member requests to Borrow Book". Your descriptions have no clear initiating action to start each particular use-case, which is essential for writing good and useful use-cases.

Plus there's no need to mention "information of the book" that's already implied by the request. Once you start analyzing the use-case and doing the design then you'll identify the information that is required by the request.


问:
Space complexity of Iterative Deepening DFS
We read on Wikipedia > Iterative deepening depth-first search that

The space complexity of IDDFS is O(bd), where b is the branching factor and d is the depth of shallowest goal.

Wikipedia also gives some decent pseudocode for IDDFS; I pythonified it:

```<code>def IDDFS(root, goal):
  depth = 0
  solution = None
  while not solution:
    solution = DLS(root, goal, depth)
    depth = depth + 1
  return solution

def DLS(node, goal, depth):
  print("DLS: node=%d, goal=%d, depth=%d" % (node, goal, depth))
  if depth >= 0:
    if node == goal:
      return node

    for child in expand(node):
      s = DLS(child, goal, depth-1)
      if s:
        return s

  return None
</code>```

So my question is, how does the space complexity include the branching factor? Does that assume that expand(node) takes up O(b) space? What if expand uses a generator that only takes constant space? In that case, would the space complexity still be a function of the branching factor? Are there situations where it is even possible for expand to be a constant-space generator?

答:
I'm studying this as we speak, so let me try to answer this question (super late, I know) in hopes of understanding IDDFS more myself.

The O(bd) cost is derived from an implementation that uses a queue to store unexplored nodes, rather than recursion. If you think about it that way, then you can imagine that we expand the root node, and add b children to the queue (to be expanded later), then we pick one child (b-1 nodes left in the queue), expand it, and add its b children (b+(b-1) nodes in the queue), and repeat this process until we reach the goal node at depth d. At this point, we have expanded d nodes, yes? And each node leading up to the goal node has contributed b-1 nodes to the queue. Hence, we have O( (d-1)(b-1)) = O(bd).

Returning to your implementation, yes, I think you're right about the O(b) term being contained in the expand function, since expand will return b children and expand will be called d-1 times. If expand uses a generator that takes constant space, sure, I think that would reduce the cost to O(d), but I don't see how expand could do anything but scale with the size of b.


问:
In domain driven design, how do I convert a database table with a primary key into a Value Object?
Lets suppose there's a database schema defined like this:

```<code>Person.mail_address_key ----- Address.address_key
Person.billing_address_key ----- Address.address_key
</code>```

A Person has a mailing address and a billing address.  As a denormalization technique, we create a separate Address table.  Most of the time the mail_address_key and the billing_address_key of a single Person will be the same value (ie: their mailing and billing address key will be the same).

In my database the Address has an identity (the address key).  But, in my domain model, I don't see a compelling reason for the Address to be an Entity, I'd like it to be a Value Object.

In DDD, is this an option? Or are Value Objects usually a group of columns (as opposed to a table)?  I'm kind of playing the devil's advocate here, because I don't think the database should dictate the domain model structure, but just making sure.

If so, where/when/how does the address lose its database identity so it can be used as a Value Object in the Domain Layer?  Or, am I supposed to keep the database identifier in the Value Object?

When the model needs to be persisted in the database, what's the process?  Am I supposed to go through a process of a) Find an address by these fields, b) if it doesn't exist, create a new one c) if it does, update the fields?

答:
DDD does not enforce DB schema at all. The value object may be implemented as a group of columns, db entity (your third solution) or simply in a denormalized form if you can use document-oriented database for instance. It depends on different circumstances what is the best option to go with.

Keep in mind that DB is only a tool for persisting your domain state. It should not force any design decision. If for some reason you have to use identity for your value object's representation in DB, do so, but do not leak this implementation detail into the domain itself. Create a wrapper/extend domain classes/whatever your framework allows and add the ID in completely separate, infrastructural class enabling the application/framework to persist the state.


问:
Which one of these would be the better way to implement object copying in c#?
I would like to be able to copy an object and only change a few values. I have come up with two different ways to do this.

```<code>// OPTION A - create a copy constructor and use property
//            initialization to change values

class SomeObject {
    public string PropertyA { get;set; }
    public string PropertyB { get;set; }

    public SomeObject() { }

    public SomeObject(SomeObject copyFrom) {
        PropertyA = copyFrom.PropertyA;
        PropertyB = copyFrom.PropertyB;
    }
}

var original = new SomeObject() {
    PropertyA = "original value",
    PropertyB = "some other original value",
}
// replace only the values I want to replace
var partialCopy = new SomeObject(original) {
    PropertyA = "some new value different from original",
};

// OPTION B - create an Option<T> type and use that

// used as constructor paramaters
public class Option<T> {

    // used in the case where you want
    // the default value of a type instead
    // of the original value (see usage below)
    public static readonly Default = new Option<T>(default(T));

    public T Value { get; private set; }

    public Option(T value) {
        Value = value;
    }

    public static implicit operator T(Option<T> o) {
        return o.Value;
    }

    public static implicit operator Option<T>(T value) {
        return new Option<T>(value);
    }
}

public class SomeObject {
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }

    public SomeObject() { }

    public SomeObject(SomeObject toCopy,
        Option<string> propertyA = null,
        Option<string> propertyB = null)
    {
        PropertyA = propertyA ?? toCopy.PropertyA;
        PropertyB = propertyB ?? toCopy.PropertyB;
    }
}

var original = new SomeObject() {
    PropertyA = "original value",
    PropertyB = "some other original value",
};
// replace only the values I want to replace
var partialCopy = new SomeObject(original,
    propertyA: "new value");
</code>```

The first implementation has much less code to maintain, but you can't enforce things in the constructor. The second is a bit more complicated due to the Option<T> class but you can, in effect, enforce rules better in a constructor at object creation. Do you think the constructor safety of OPTION B overrides the complexity, making it the better choice. Or should I use the simpler OPTION A due to ease of maintenance?

These are simple data transfer objects. They generally have a lot of properties. I'm trying to avoid creating objects like template, templateB, templateB.2, etc. when I can just copy the current object and change the properties I need. For example, properties A,B, and C need to be set to this value when a particular rule passes. However further in the process, properties D,E, and F will need different values based on other rules. I'm trying to avoid code like the following:

```<code>  // I'm trying to avoid this
  ResponseObject SomeMethod(bool inputA, bool inputB) {
     var myObject = CreateObjectFromTemplateA(); // has same values for A,B,C
     if(inputA) {
         myObject.D = "some value";
         myObject.E = "some value";
         myObject.F = "some value";
     } else if (inputB) {
         myObject.D = "some other value";
         myObject.E = "some other value";
         myObject.F = "some other value";
     }
     return myObject;
  }

  // and do something like this instead
  ResponseObject SomeMethod(bool inputA, bool inputB) {
      var defaultValue = CreateFromTemplateA()
      return inputA ? new ResponseObject(defaultValue) { D = "some value",
                                                         E = "some value",
                                                         F = "some value",},
           : inputB ? new ResponseObject(defaultValue) { D = "some other value",
                                                         E = "some other value",
                                                         F = "some other value",},
                    : defaultValue;
  }

  // in some cases it's as simple as one property change
  // and here is where the first method of property initialization
  // breaks down
  ResponseObject SomeMethod(bool inputA, bool inputB) {
      return new ResponseObject(CreateFromTemplateA()) {
             D = inputA ? "some value"
               : inputB ? "some other value
                        : CreateFromTemplateA(), // a second object created
      };
  }

  // here is where the constructor initialization helps
  ResponseObject SomeMethod(bool inputA, bool inputB) {
      return new ResponseObject(CreateFromTemplateA(), // with this method CreateFromTemplateA() could be a property instead of a method call
          d: inputA ? "someValue"
           : inputB ? "someValue"
                    : null // null here indicates use the property value from CreateFromTemplateA()
      );
  }
</code>```

答:
There are several ways to achieve this.

As mentioned in the other comments, you must consider if the object is a simple property object or has property references to other objects, and who "owns" or "manages" those object references or objects.

Example of simple object:

```<code>public class PersonClass
{
  public string FirstName;
  public string LastName;
  public DateTime BirthDate;
  public bool IsMarried;

  public PersonClass GetSimpleCopy()
  {
    PersonClass Result = new PersonClass();
      Result.FirstName = this.FirstName;
      // assign other properties
    return Result;
  }
} // class PersonClass
</code>```

Check that this is a very simple way to duplicate an object.

Note that I skipping "copying" constructors.

Example of object with references to other objects, that are managed ("created" / "destroyed" ) by the main object:

```<code>public class PersonClass
{
  public string FirstName;
  public string LastName;
  public DateTime BirthDate;
  public bool IsMarried;

  public PersonClass GetSimpleCopy() { ... }
} // class PersonClass

public class ItemClass
{
  public string ProductID;
  public string ProductName;
  public Float Price;
  public int Qty;

  public ItemClass GetSimpleCopy() { ... }
} // class ItemClass

public class SaleClass
{
  protected bool _Referenced;
  public float Total;

  public PersonClass Customer;
  public List<ItemClass> Items;

  public bool Referenced()
  {
    bool Result = false;
      Result = this._Referenced;
    return Result;
  } // bool Referenced()

  public ItemClass GetSimpleCopy()
  {
    ItemClass Result = new ItemClass();
      Result._Referenced = false;
      Result.Total = this.Total;
      // explicitly return "empty"
      Result.Customer = null;
      Result.Items= new List<ItemClass>();
    return Result;
  } // ItemClass GetSimpleCopy()

  public ItemClass GetReferencedCopy()
  {
    ItemClass Result = new ItemClass();
      Result._Referenced = true;
      Result.Total = this.Total;
      // explicitly return references
      Result.Customer = this.Customer;
      Result.Items = this.Items;
    return Result;
  } // ItemClass GetReferencedCopy()

  public ItemClass GetComplexCopy()
  {
    ItemClass Result = new ItemClass();
      Result._Referenced = false;
      Result.Total = this.Total;
      // explicitly make a copy of subobjects
      Result.Customer = this.Customer.GetSimpleCopy();
      // copy each item
      Result.Items = this.Items.GetSimpleCopy();
    return Result;
  } // ItemClass GetComplexCopy()
} // class SaleClass
</code>```

Remember that O.O. Programming Languages that support object references, is preferred to copy the reference instead of the whole object.

Yet, there are cases where the full copy is required. In case of complex or composed objects, its better to provide a property flag that indicates if subobjects are just references or are managed by the main object.

Sometimes, a main object may manage some subobjects, but, also have a reference to other objects that may not be required to be managed or to be copied. In those cases, a flag for each subobject helps.

Note that the function "Referenced" indicates if a composed / complex object manages subojects, and, the different copy methods indicate what kind of copying was applied.

Note that, I intentionally skip constructors, and use specific methods with a more clear identifier.

Cheers.

Body:
There are several ways to achieve this.

As mentioned in the other comments, you must consider if the object is a simple property object or has property references to other objects, and who "owns" or "manages" those object references or objects.

Example of simple object:

public class PersonClass
{
  public string FirstName;
  public string LastName;
  public DateTime BirthDate;
  public bool IsMarried;

  public PersonClass GetSimpleCopy()
  {
    PersonClass Result = new PersonClass();
      Result.FirstName = this.FirstName;
      // assign other properties
    return Result;
  }
} // class PersonClass

Check that this is a very simple way to duplicate an object.

Note that I skipping "copying" constructors.

Example of object with references to other objects, that are managed ("created" / "destroyed" ) by the main object:

public class PersonClass
{
  public string FirstName;
  public string LastName;
  public DateTime BirthDate;
  public bool IsMarried;

  public PersonClass GetSimpleCopy() { ... }
} // class PersonClass

public class ItemClass
{
  public string ProductID;
  public string ProductName;
  public Float Price;
  public int Qty;

  public ItemClass GetSimpleCopy() { ... }
} // class ItemClass

public class SaleClass
{
  protected bool _Referenced;
  public float Total;

  public PersonClass Customer;
  public List<ItemClass> Items;

  public bool Referenced()
  {
    bool Result = false;
      Result = this._Referenced;
    return Result;
  } // bool Referenced()

  public ItemClass GetSimpleCopy()
  {
    ItemClass Result = new ItemClass();
      Result._Referenced = false;
      Result.Total = this.Total;
      // explicitly return "empty"
      Result.Customer = null;
      Result.Items= new List<ItemClass>();
    return Result;
  } // ItemClass GetSimpleCopy()

  public ItemClass GetReferencedCopy()
  {
    ItemClass Result = new ItemClass();
      Result._Referenced = true;
      Result.Total = this.Total;
      // explicitly return references
      Result.Customer = this.Customer;
      Result.Items = this.Items;
    return Result;
  } // ItemClass GetReferencedCopy()

  public ItemClass GetComplexCopy()
  {
    ItemClass Result = new ItemClass();
      Result._Referenced = false;
      Result.Total = this.Total;
      // explicitly make a copy of subobjects
      Result.Customer = this.Customer.GetSimpleCopy();
      // copy each item
      Result.Items = this.Items.GetSimpleCopy();
    return Result;
  } // ItemClass GetComplexCopy()
} // class SaleClass

Remember that O.O. Programming Languages that support object references, is preferred to copy the reference instead of the whole object.

Yet, there are cases where the full copy is required. In case of complex or composed objects, its better to provide a property flag that indicates if subobjects are just references or are managed by the main object.

Sometimes, a main object may manage some subobjects, but, also have a reference to other objects that may not be required to be managed or to be copied. In those cases, a flag for each subobject helps.

Note that the function "Referenced" indicates if a composed / complex object manages subojects, and, the different copy methods indicate what kind of copying was applied.

Note that, I intentionally skip constructors, and use specific methods with a more clear identifier.

Cheers.


问:
saving connectivity information in a nodes/edges network
I want to implement the A* algorithm. I have a network with Nodes and Edges, both are classes.

Now, I am unsure how to approach the connectivity information. Should a node know which edges depart from it? Should an edge know which two nodes it connects?

I thought both answers were true, but then there are circular dependencies, i.e. when copying a node, it copies all the edges it has, which, in turn, copy all the nodes they connect, and so on.

Maybe it is better to save all connectivity problems in the Network class? But then I have to explicitly create them and have to update them manually if I delete or add nodes/edges.

What is a good way to approach this?

答:
Unless your edges have attributes (which you didn't state) the simplest way is to not add edge A → B if A → B already exists. This is how decentralized flooding mechanisms (e.g.
USENET) keep from forming cycles.

As far as what objects should know what they are connected to, you've got a space/time trade-off: you can have nodes know edges or edges know nodes or both. To do useful stuff with graphs, both is probably the best otherwise you'll spend a lot of time looking for elements.


答:
I don't see any DDD's special requirements in this case, you can model mailing and billing addresses as person's properties and still store them in a separate table, for example:

```<code>Person
+ MailingAddress : Address
+ BillingAddress : Address
</code>```

or

```<code>Person
+ MailingAddressID
+ MailingAddress : Address
+ BillingAddressID
+ BillingAddress : Address
</code>```

Title: In domain driven design, how do I convert a database table with a primary key into a Value Object?

Body:
Lets suppose there's a database schema defined like this:

```<code>Person.mail_address_key ----- Address.address_key
Person.billing_address_key ----- Address.address_key
</code>```

A Person has a mailing address and a billing address.  As a denormalization technique, we create a separate Address table.  Most of the time the mail_address_key and the billing_address_key of a single Person will be the same value (ie: their mailing and billing address key will be the same).

In my database the Address has an identity (the address key).  But, in my domain model, I don't see a compelling reason for the Address to be an Entity, I'd like it to be a Value Object.

In DDD, is this an option? Or are Value Objects usually a group of columns (as opposed to a table)?  I'm kind of playing the devil's advocate here, because I don't think the database should dictate the domain model structure, but just making sure.

If so, where/when/how does the address lose its database identity so it can be used as a Value Object in the Domain Layer?  Or, am I supposed to keep the database identifier in the Value Object?

When the model needs to be persisted in the database, what's the process?  Am I supposed to go through a process of a) Find an address by these fields, b) if it doesn't exist, create a new one c) if it does, update the fields?

Body:
I don't see any DDD's special requirements in this case, you can model mailing and billing addresses as person's properties and still store them in a separate table, for example:

Person
+ MailingAddress : Address
+ BillingAddress : Address

or

Person
+ MailingAddressID
+ MailingAddress : Address
+ BillingAddressID
+ BillingAddress : Address


问:
How to avoid large function arity / exposure of underlying implementation
Currently reading Clean Code, and the authors seem to imply that any function with an arity greater than 3 should be avoided at all costs.

I am unfortunately running into an issue where I am faced with a class method with an arity of 4 (5 if you count self)

```<code> def start_job(self, operation, name, external_id, format):
    ...
</code>```

All of the parameters can vary, and are necessary to start the job. However, if I think about encapsulating all of those parameters in some sort of class

```<code>class Job(object):
    def __init__(self, operation, name, external_id, format):
</code>```

but then all of those parameters would be necessary for the __init__, and would still need to expose the underlying structure of the object to the start_job function. At this point, it would seem like feature envy as well and would make sense to change the start_job function over to the Job class and just call it start.

Any ideas on how to avoid this smell?

答:
Do the members of Job logically cohere into an object? Yes.
What can you do with a Job? Start it, stop it, query its state.

Sounds like you've got a bona fide object there with start(), stop(), query() instance methods.


问:
What is the best C++ interview question?
If you could ask a C++ programmer one question to measure their C++ skills, what would it be?

The question I think is best is: Can you call "delete this;" inside a member function? (I put this as a link so you can think it through first, then go to The Best C++ Interview Question – Ever! to see the correct answer.)

I don't ask this because I expect most people to know the answer. If they did it would not be that useful a question. I ask to see if they can work their way to the correct answer and how they do so.

答: The best C++ interview question would be a programming problem, not a quiz question.</p>

ContentLicense: CC BY-SA 2.5


答:
This really isn't answerable without knowing the exact case you are trying to solve.  The reason they call them "code smells" is not because the "smell" itself is bad but rather because it indicates that there is something else wrong, a metaphorical pile of crap underneath generating that smell.

As such, the answer generally is not to directly attack the smell itself.  That's no better than spraying the crap with lysol.  The answer is to try to figure out what in the underlying design pushed you to use a method with four parameters.  Maybe examining the smell will bring this out, or maybe you'll decide that it was just a whiff of compost and maybe not so bad.

In this case, four parameters isn't much of a stink.  It's when you reach ten or fifteen that things stink to high heaven.

One way to see if this is a real issue is to look at the code inside the function.  Is it a set of elif blocks, basically a case statement controlled by one of your parameters?  If so, maybe the method should be broken up along those lines.

Are you passing the same set of parameters to a set of methods?  Then maybe you should have a class controlling those values with members for each of the original methods.

Are some of the parameters combined in particular ways inside the method to make a single value?  Maybe it could be pulled up out of the function.  (For instance, are you creating a filename that looks like name + '.' + extension where extension depends on format?

Does a parameter almost always take a particular value?  Then make it a default. While not reducing the "arity", it does reduce the cognitive load required to use the function.

Title: How to avoid large function arity / exposure of underlying implementation

Body:
Currently reading Clean Code, and the authors seem to imply that any function with an arity greater than 3 should be avoided at all costs.

I am unfortunately running into an issue where I am faced with a class method with an arity of 4 (5 if you count self)

```<code> def start_job(self, operation, name, external_id, format):
    ...
</code>```

All of the parameters can vary, and are necessary to start the job. However, if I think about encapsulating all of those parameters in some sort of class

```<code>class Job(object):
    def __init__(self, operation, name, external_id, format):
</code>```

but then all of those parameters would be necessary for the __init__, and would still need to expose the underlying structure of the object to the start_job function. At this point, it would seem like feature envy as well and would make sense to change the start_job function over to the Job class and just call it start.

Any ideas on how to avoid this smell?


问:
Is it possible/good idea to reduce chance of crashing by catching Error?
I have a class the implements A which will run a certain method of class B. There is a requirement that this A should never crash when running this operation (which is not possible, right?).

To reduce the chance of crashing I'm catching Throwable around the operation, like so:

```<code>public void method(B b)
{
    try
    {
        b.operation
    }
    catch(Throwable e)
    {
        //Log e
        //Clean up stuff
    }
}
</code>```

My questions are:

Would this actually help in reducing crashes caused by any thrown Error?

Is it a good idea to ever catch an Error?

答:
I won't write a java program without catching Throwable at the
top level of every process.   The caught error is (by definition)
unexpected, and is a bug that needs to be logged and fixed.  The
errors you catch this way will surprise you, and you will never
learn of them unless you make every possible attempt to get the
word back from the real world to your development desk.


答:
If all of these parameters are always required (never optional), vary independently, have no sensible sub groups, and have widely varying values then it will be tough to do better than you've already done.  Named Arguments can make the long list less confusing to read.

If that's not exactly the case then there may be room for improvement.  Ask yourself:

Are all the parameters required or are some optional?  If optional they should have a default.  Make attributes and use a property or setter to change the default.  Only keep required ones in __init___.

Are any of the parameters related?  If I know two of them can I do anything useful?  If so make an object for them that does this useful thing and see if it can also help you do your thing.

If I know one of them can I learn what the other is?  If so you're probably providing redundant information.  Figure out what you can live without.

Do any of the parameters have a limited number of states?  For example are there only 5 things operation can be?  Maybe 5 methods would be a better idea, or even 5 classes.

There are a lot of patterns that can help with this problem.  The GoF construction patterns, in particular builder and parameter object.  Also the python version of Josh Bloch's builder might help.  Whether it's 4 or 14 parameters you should always look for a way to simplify how your code is used.


答:
That depends a lot on what kind of C++ is written at your company. (When I had to hire C++ programmers, I never asked about delete, because I asked them about techniques to avoid having to write delete altogether.)

Ideally, you want to hire people that write code above the level of what your team currently writes, but not too high above it, unless you want to combine this with training the team to take it to a higher level.

Title: What is the best C++ interview question?

Body:
If you could ask a C++ programmer one question to measure their C++ skills, what would it be?

The question I think is best is: Can you call "delete this;" inside a member function? (I put this as a link so you can think it through first, then go to The Best C++ Interview Question – Ever! to see the correct answer.)

I don't ask this because I expect most people to know the answer. If they did it would not be that useful a question. I ask to see if they can work their way to the correct answer and how they do so.


问:
Why does dependency injection encourage collaboration to be exposed via constructors?
The general approach to DI that I see in answers like
So Singletons are bad, then what? encourages
business objects that collaborate with other objects to (a) not
directly create those instances and (b) have them passed in at
construction. I can understand (a), but not (b). This seems to occur
most often in response to overuse of Singletons. But why not just have
a modified approach to singleton:

```<code>class SingleInstance {
  virtual foo();
  virtual bar();

  static SingleInstance getInstance() {
    if(instance_ == null) {
      instance_ = new SingleInstance();
    }
    return instance_;
  }

  void setMockInstance(SingleInstance s) {
    assert(instance_ == null);
    instance_ = s;
  }

  static SingleInstance instance_;
}
</code>```

So now this is no longer a Singleton with a capital S (per Misko
Hevery) but in this case still enforces one instance. All code that
wants to access the single instance can still call S::getInstance()
without cluttering up their constructors by explicitly requiring the
instance to be passed in. The default can still be still lazily
initialized in the production code, but for test can still be mocked.

In the referenced answer the first benefit of DI is listed as:

```<code>It makes the code easier to read; you can clearly understand from
the interfaces exactly what data the dependent classes depend on.
</code>```

But why is that not a violation of encapsulation? Do I really need to
know from the public interface everything that accesses the
SingleInstance/Database/etc?

Assume you have a Database and 30 TableGateway classes responsible
for CRUD operations on those tables. In the DI approach TableGateway
constructors would accept the Database on in its constructor. Then a
business logic class would accept the tables it collaborates with/uses:

```<code>class BusinessLogic {
  BusinessLogic(Table1 t1, Table2 t2, Table3 t3);
  void doBusiness() {
    t1_.query(...);
    t2_.insert(...);
    t3_.update(...);
  }
}
</code>```

How is that churn of explicit dependencies in the constructor
advisable?

答:
The reason I give dependencies to constructors is:

Most of the time the dependencies are required, so why not give them to the constructor

Giving them to the object in an other way makes using them a bit more complex, since you have to make sure you have the dependency

Of course this doesn't really count when you are using a framework that controls the dependency injection, because the framework will make sure all the dependencies are set before returning the requested object.


答:
Static data (including singleton instances) is problematic for a number of reasons.  It's not thread-friendly.  You have added a method to set the single instance to a mock instance.  Presumably that is done to support unit testing.  This will fail if tests are run in parallel and require different mocks for your Singleton.  Worse, the tests will fail when run together but will pass when run separately.

Even without running tests in parallel, static data introduces a global state that is retained between tests.  A test that depends on static data could pass reliably when run alone against the initial global state, but consistently fail if run after another test that modifies the global state.

For these reasons, mutable static data should be avoided.  I have seen many more incorrect uses of mutable static data than correct uses.

Title: Why does dependency injection encourage collaboration to be exposed via constructors?

Body:
The general approach to DI that I see in answers like
So Singletons are bad, then what? encourages
business objects that collaborate with other objects to (a) not
directly create those instances and (b) have them passed in at
construction. I can understand (a), but not (b). This seems to occur
most often in response to overuse of Singletons. But why not just have
a modified approach to singleton:

```<code>class SingleInstance {
  virtual foo();
  virtual bar();

  static SingleInstance getInstance() {
    if(instance_ == null) {
      instance_ = new SingleInstance();
    }
    return instance_;
  }

  void setMockInstance(SingleInstance s) {
    assert(instance_ == null);
    instance_ = s;
  }

  static SingleInstance instance_;
}
</code>```

So now this is no longer a Singleton with a capital S (per Misko
Hevery) but in this case still enforces one instance. All code that
wants to access the single instance can still call S::getInstance()
without cluttering up their constructors by explicitly requiring the
instance to be passed in. The default can still be still lazily
initialized in the production code, but for test can still be mocked.

In the referenced answer the first benefit of DI is listed as:

```<code>It makes the code easier to read; you can clearly understand from
the interfaces exactly what data the dependent classes depend on.
</code>```

But why is that not a violation of encapsulation? Do I really need to
know from the public interface everything that accesses the
SingleInstance/Database/etc?

Assume you have a Database and 30 TableGateway classes responsible
for CRUD operations on those tables. In the DI approach TableGateway
constructors would accept the Database on in its constructor. Then a
business logic class would accept the tables it collaborates with/uses:

```<code>class BusinessLogic {
  BusinessLogic(Table1 t1, Table2 t2, Table3 t3);
  void doBusiness() {
    t1_.query(...);
    t2_.insert(...);
    t3_.update(...);
  }
}
</code>```

How is that churn of explicit dependencies in the constructor
advisable?


答:
Your modified approach to singleton is still a singleton, and has most of the drawbacks of a singleton:

It still introduces high coupling across the application - that is, if one day you want to refactor away from singleton, you will have a hard time doing it;

It still gives a way for any component to collaborate with the singleton - meaning that potentially, the singleton can communicate with any piece of the system - but if you go for any kind of layered architectural pattern (MVC, MVVM, 3-tier), then the singleton is a point that has to be controlled.

Encapsulation is related to the fact that an object exposes the operations it supports without requiring that clients know about its implementation - but when you invoke a constructor, the object does not exist yet. The constructor is an implementation detail of the object, equivalent to a static method. In other words, once the object is created, the constructor arguments are irrelevant to the operation of the object.

As for the "churn" of explicit dependencies, making the dependencies explicit is one of the goals of constructor injection. If you have too many, it is taken as a sign that a refactoring, or a reorganization, is in order. (E.g. group related tables into a logical group).


问:
C# Dependency Injection Placement
This is my first time using Unity so bear with me for a moment.  I have a sample Visual Studio 2012 project with 4 projects (but only two of these projects will be used with Unity).  This is the following setup of the projects:

Database - WinForm project that displays a Master Detail Form

DatabaseUtilities - A class library that implements the Repository pattern.  The interface is called ISampleRepository.cs and the type is called SampleRepository.cs

Project Setup http://www.omnicom-innovations.com/Snippets/Images/Unity/UnityQuestion2.png

I've been reading on Dependency Injection and I understand that the UnityContainer code gets placed in the starting location of where the application is going to run.

Should it go in Database.Program.cs or in a Bootstrapper.cs class that resides in the DatabaseUtilities project?

I ask because Program.cs is technically the entry point to the Database WinForm project.

Here's my code for Bootstrapper.cs:

```<code>using Microsoft.Practices.Unity.Configuration;

namespace DatabaseUtilities
{
    public class Bootstrapper
    {
        private static UnityContainer _container;

        public static ISampleRepository<Employee> LoadSampleRepository()
        {
            _container = new UnityContainer();
            _container.RegisterType(typeof(ISampleRepository<Employee>), typeof(SampleRepository));
            var obj = _container.Resolve<ISampleRepository<Employee>>();

            return obj;
        }
    }
}
</code>```

I'm thinking of referencing the Bootstrapper.cs from Program.cs in the Database project.

But would this be considered a best practice?  Furthermore, I want to make sure that I don't shoot myself in the foot later on.  Let's say I decide to implement another form from the MasterDetail form and I need to perform a different CRUD operation (i.e. an update operation).  I want to be able to use my class that implements IRepository.

Am I looking at this from the right angle?

答:
Basically it would not be a good idea to put container logic inside a library. When you want to use the DatabaseUtilities library in another project that uses another dependency injection framework, you still have the dependency with Unity.

So in this case it would be better to move the bootstrap class to your main project.

Putting the bootstrap logic inside the Program.cs or inside a separate class is basically a matter of opinion, but thinking about the Single Responsibility Principle I would say keep them separate.

Alternatively you could create another project that is purely responsible for the configuration part of the container, but that is probably overkill in this situation.

Yet another alternative is to merge both projects into one, because do you really need to have a project separation, can't you just put the DatabaseUtilities in a separate namespace inside your main project?

Title: C# Dependency Injection Placement


问:
Approach to send data updates to subscriber clients C#
We would want to send timely emails to subscribers about updates/changes to the database.
What would be an optimum approach to this.
Is considering SignalR a good path?

Example:
Let us say we have a list of phones with specific features in the database. User wants to get notified whenever a new phone with front camera of 8 Mega pixels comes into market.

Considered storing email subscribers, and their conditions, check database every night, and send emails.

Read about SignalR and real time updates but could not wrap my head over its applications. Can it be applied to scenario that I have mentioned?

答:
Sending emails to subscribers every once in a while isn't really a real-time requirement. Subscribers would read your emails after a few minutes at the very least, so why bother sending them within microseconds of updates.

It would be best suited for a scheduled task that runs in set intervals like 60 seconds.

Here's a simple task scheduling technique that StackOverflow itself used in its early days:

At startup, add an item to the HttpRuntime.Cache with a fixed expiration.

When cache item expires, do your work (send your emails)

Re-add the item to the cache with a fixed expiration.

This goes into Global.asax:

```<code>private static CacheItemRemovedCallback OnCacheRemove = null;

protected void Application_Start(object sender, EventArgs e)
{
    AddTask("DoStuff", 60);
}

private void AddTask(string name, int seconds)
{
    OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
    HttpRuntime.Cache.Insert(name, seconds, null,
        DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
        CacheItemPriority.NotRemovable, OnCacheRemove);
}

public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
{
    // do stuff here if it matches our taskname, like WebRequest
    // re-add our task so it recurs
    AddTask(k, Convert.ToInt32(v));
}
</code>```

Source: http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/

Body:
Sending emails to subscribers every once in a while isn't really a real-time requirement. Subscribers would read your emails after a few minutes at the very least, so why bother sending them within microseconds of updates.

It would be best suited for a scheduled task that runs in set intervals like 60 seconds.

Here's a simple task scheduling technique that StackOverflow itself used in its early days:

At startup, add an item to the HttpRuntime.Cache with a fixed expiration.

When cache item expires, do your work (send your emails)

Re-add the item to the cache with a fixed expiration.

This goes into Global.asax:

private static CacheItemRemovedCallback OnCacheRemove = null;

protected void Application_Start(object sender, EventArgs e)
{
    AddTask("DoStuff", 60);
}

private void AddTask(string name, int seconds)
{
    OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
    HttpRuntime.Cache.Insert(name, seconds, null,
        DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
        CacheItemPriority.NotRemovable, OnCacheRemove);
}

public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
{
    // do stuff here if it matches our taskname, like WebRequest
    // re-add our task so it recurs
    AddTask(k, Convert.ToInt32(v));
}

Source: http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/


问:
Logic based on modified fields of a Hibernate entity
I have a Hibernate entity object MyObject with several attributes and a service MyObjectService containing business logic dealing with MyObject. I also have a view model dealing with user input/output which uses MyOjectService. This service contains method updateMyObject(MyObject o) which is called by the view model when user changes some attributes, and it saves these changes into the database.

When some (not all) attributes of MyObject are updated, I need to notify an external system. I'm trying to figure out a best way of implementing this functionality. These are the solutions I came up with so far:

Method MyObjectService.update(MyObject o) would get a second boolean parameter saying whether to send the notification to the external system. This is the simplest solution, but It's probably not good to let the view model (which calls the method) decide whether to send the notification or not. I'd rather have this decision in the service.

The view model would keep a copy of the original state of the object along with the modified state. Method update would then have 2 arguments (before and after) and it would check whether the attributes which need to be notified of are changed. This would result in a pretty ugly condition like if (before.attr1 != after.attr1 or before.attr2 != after.attr2 or ... ) containing a large number of attributes which can grow in the future.

Have a separate update method in MyObjectService for each attribute of MyObject. This way, each method would decide whether the notification has to be sent or not. This is probably the cleanest way, but I'd have to have a large number of update methods (1 for each attribute).

So each of these solutions has its disadvantages. Which one would you use? Or do you have a different idea how to do this? Is there some way I could use Hibernate to help me with this? (I tried to find out whether I could use Hibernate to find out which attributes are modified, but I didn't find a satisfactory solution).

答:
If I understand you correctly, you have two kinds of state-objects:

The @Entity which is used in the persistence-context (Hibernate)

The "viewmodel", which deals with user input and as you describe: »which uses MyOjectService«

So your dataflow is from the user to the viewmodel and from the viewmodel to the Entity - we could neglect the persitence for your problem.

In this scenario is a third component - the MyOjectService involved and there is a strong coupling between the view-model and this service.

My suggestion is: implementing an observer-pattern.

Everytime, the viewmodel is changed, observers are notified:

1) One observer is responsible to call the MyOjectService on any change of the viewmodel

2) A second observer/model is responsible for managing the state to trigger the notification. It could consist only of three booleans (attribute1Set?,attribute2Set?, attribute3Set?) and if all three were set, an event is emitted to update the external service. After that, the attributes are resetted.

The workflow would look like the following:

Entity is fetched from db->Viewmodel filled->Trigger reset->Viewmodelchange leads to an Update in the database and eventually to changes in the Triggerobject->Triggerobject changes state and checks, whether it is necessary to update the external systems or not->Trigger fired=Trigger reset

You get the point;)

So you have clear responsibilities:

1) The @Entity is only for persistence

2) The Viewmodel is only for user-interaction

3) The "Trigger" is only for triggering the external sevice

The observer-pattern helps you decoupling and separating these responsibilities.


答:
I would ask them what they like about C++0x. From this I could "bucket" them into various stereotypes:

super old school, uses C++ compilers to compile C code

old school, scared of (or sees no point to) STL, hasn't been keeping up with the changes

loves lambdas, loves STL getting faster from rvalue references, big RAII fan, hot to use shared_ptr, unique_ptr etc

is bitter because all the boost code written over the last few years will need to be adapted to use C++0x equivalents

insane template metaprogrammer who makes my head explode while answering a relatively short question

Chances are some of these buckets are perfect for you and some are "thanks for coming in". As a question that gets you a lot of information fast, this is my winner.


问:
Updating an Entity through a Service
I'm separating my software into three main layers (maybe tiers would be a better term):

Presentation ('Views')

Business logic ('Services' and 'Repositories')

Data access ('Entities' (e.g. ActiveRecords))

What do I have now?

In Presentation, I use read-only access to Entities, returned from Repositories or Services, to display data.

```<code>$banks = $banksRegistryService->getBanksRepository()->getBanksByCity( $city );

$banksViewModel = new PaginatedList( $banks ); // some way to display banks;
                                               // example, not real code
</code>```

I find this approach quite efficient in terms of performance and code maintanability and still safe as long as all write operations (create, update, delete) are preformed through a Service:

```<code>namespace Service\BankRegistry;

use Service\AbstractDatabaseService;
use Service\IBankRegistryService;
use Model\BankRegistry\Bank;

class Service
    extends AbstractDatabaseService
    implements IBankRegistryService
{
    /**
     * Registers a new Bank
     *
     * @param string $name                  Bank's name
     * @param string $bik                   Bank's Identification Code
     * @param string $correspondent_account Bank's correspondent account
     *
     * @return Bank
     */
    public function registerBank( $name, $bik, $correspondent_account )
    {
        $bank = new Bank();

        $bank
            -> setName( $name )
            -> setBik( $bik )
            -> setCorrespondentAccount( $correspondent_account );

        if( null === $this->getBanksRepository()->getDefaultBank() )
            $this->setDefaultBank( $bank );

        $this->getEntityManager()->persist( $bank );

        return $bank;
    }

    /**
     * Makes the $bank system's default bank
     *
     * @param Bank $bank
     * @return IBankRegistryService
     */
    public function setDefaultBank( Bank $bank )
    {
        $default_bank = $this->getBanksRepository()->getDefaultBank();

        if( null !== $default_bank )
            $default_bank->setDefault( false );

        $bank->setDefault( true );

        return $this;
    }
}
</code>```

Where am I stuck?

I'm struggling about how to update certain fields in Bank Entity.

Bad solution #1: Making a series of setters in Service for each setter in Bank; - seems to be quite reduntant, increases Service interface complexity and proportionally decreases it's simplicity - something to avoid if you care about code maitainability. I try to follow KISS and DRY principles.

Bad solution #2: Modifying Bank directly through it's native setters; - really bad. If you'll ever need to move modification into the Service, it will be pain. Business logic should remain in Business logic layer. Plus, there are plans on logging all of the actions and maybe even involve user permissions (perhaps, through decorators) in future, so all modifications should be made only through the Service.

Possible good solution: Creating an updateBank( Bank $bank, $array_of_fields_to_update) method; - makes the interface as simple as possible, but there is a problem: one should not try to manually set isDefault flag on a Bank, this operation should be performed through setDefaultBank method. It gets even worse when you have relations that you don't want to be directly modified.

Of course, you can just limit the fields that can be modified by this method, but how do you tell method's user what they can and cannot modify? Exceptions?

答:
Maybe CQRS is worth looking at for you.

http://martinfowler.com/bliki/CQRS.html

More specifically:

Interacting with the command-model naturally falls into commands or events, which meshes well with Event Sourcing.

So in this pattern, you send updates to the domain model using commands sent via. events.

Title: Updating an Entity through a Service


问:
Website testable design
I have developed two web services. The main service is a RESTful service (using DB), and another UI service that uses the RESTful service.

Say I want to test the UI for now (integration tests), every test will makes changes in the prod DB. More then that, if in the RESTful service, there are one-way functions for security reasons. I mean that functions that can not be revert (Say if mark item as 'done', I can't edit or delete it anymore)?

This things are very logical, the most websites I know have the same situation. All these websites are not testable?

答: Given HATEOAS, you only need to change the base URL for your RESTful service to point the UI service to another implementation of it. So set up a staging version of your UI and test it against a staging version of the data service, making that one change.</p>

Title: Website testable design


答:
First of all, you shouldn't be testing against your production database. If you ever need to rerun your tests after the application has gone live (and you will need to do that), you run a serious risk of losing or corrupting data that is vital to the business.

So, instead of testing against the production database, you test against a test database (which should structurally be a copy of the production one). Then you can also add facilities to your test harness to reset that test database to a known state just before or after running a particular test.

This way, you can test the correct (inter-)operation of the two web services.

If the correct operation of the RESTful service can be presumed, you can also opt for a fake/mock of the RESTful service, which gives all the expected responses for the particular test, but doesn't actually persist anything.

Title: Website testable design

Body:
I have developed two web services. The main service is a RESTful service (using DB), and another UI service that uses the RESTful service.

Say I want to test the UI for now (integration tests), every test will makes changes in the prod DB. More then that, if in the RESTful service, there are one-way functions for security reasons. I mean that functions that can not be revert (Say if mark item as 'done', I can't edit or delete it anymore)?

This things are very logical, the most websites I know have the same situation. All these websites are not testable?


答:
Since you have to do unit testing for the REST API, I would assume you are using mock objects for those, rather than interact directly with the database. This should give you a framework of proper "valid" responses from the API already - what I'm getting at is that when you test, you should know you're in "test mode" (either through some global environment variable, separate testing environment or an extra parameter you set in the requests r somewhere else in your workflows). So if you are in test mode, your REST API should return mock objects to your client in the response, without affecting your database records in any way.

Since these are tests on the client side, your concern should be strictly to test the client interaction, because proper API behavior is tested by the REST server-side unit tests, so you should assume that the API itself behaves as it's supposed to.

Title: Website testable design


问:
Why is reading from memory not a side-effect but reading from a file is?
What does exactly make reading from the process memory a pure operation? Suppose I created an array of 100 integers in the global memory and then took the 42th element of this array. It is not a side effect, right? So why is reading the same array of 100 integers from a file a side-effect?</p>

答:
If the memory you access can change, then it is indeed a side effect.

For example, in Haskell, the function to access a mutable array (IOArray) has type

```<code>Ix i => IOArray i e -> i -> IO e
</code>```

(slightly simplified for our purposes). While accessing an immutable array has type

```<code>Ix i => Array i e -> i -> e
</code>```

The first version returns something of type IO e which means it has I/O side effects. The second version simply returns an element of type e without any side effects.

In case of accessing a file, you simply cannot know at compile time whether the file will ever change during a run of the program. Therefore, you have to always treat it as an operation with potential side effects.

Body:
If the memory you access can change, then it is indeed a side effect.

For example, in Haskell, the function to access a mutable array (IOArray) has type

Ix i => IOArray i e -> i -> IO e

(slightly simplified for our purposes). While accessing an immutable array has type

Ix i => Array i e -> i -> e

The first version returns something of type IO e which means it has I/O side effects. The second version simply returns an element of type e without any side effects.

In case of accessing a file, you simply cannot know at compile time whether the file will ever change during a run of the program. Therefore, you have to always treat it as an operation with potential side effects.


答:
Reading from memory does not influence other functions and is therefore side-effect-free. Reading from a file will typically move the file's position pointer, so that when you read again you read the data after what you have already read, so one read function changes the result of other read functions, which is a side effect. If you instead open, read and close a file in one go than this side effect disappears, but that is not feasible for big files. Additionally, depending on how you open the file, it may become locked after opening it, so the first try to open and read the file succeeds while following tries will fail with a File Already Open error, which again is a side effect.

Creating a side-effect-free reading function that reads the file in one go and allows multiple reads at the same time is difficult because there are file writing functions which get influenced by the reading function and getting rid of file writing functions is again not feasible.

Title: Why is reading from memory not a side-effect but reading from a file is?

Body: What does exactly make reading from the process memory a pure operation? Suppose I created an array of 100 integers in the global memory and then took the 42th element of this array. It is not a side effect, right? So why is reading the same array of 100 integers from a file a side-effect?</p>


答:
If you have a shared file handle then reading a file will move that file handle to the position where you have read, and will leave it at that position.

If you have two threads with separate file handles to the same file, reading from one will have no noticeable side effect on the other.

However in both these cases, memory reading and file reading, there could be a hidden side effect of operator system caching.


问:
What is proper order of pull requests and testing?
We want to setup proper development workflow.
We have two main branches: master(release branch) and develop(working branch).
We want to use pull requests properly.
We see two ways how to do this:

The first one:

Create new branch for feature.

Implement feature.

Merge to develop branch.

Test develop branch.

Confirm that everything works.

Create pull request onto master branch.

Merge pull request.

Steps 4 and 7 can return to step 1.

The second one:

Create new branch for feature.

Implement feature.

Create pull request onto develop branch.

Merge pull request.

Test develop branch.

Confirm that everything works.

Merge develop into master.

Steps 4 and 6 can return to step 1.

Which one is better? Or there is better way that I described?

We have 3 team members: developer, tester and reviewer.

答:
I would say that whether you use the first approach ('you verify') vs. the second approach ('we verify') depends on the setup and organization of your team.

A small group of team members that work closely together (often in the same physical place but not always) often prefers the first approach.

A widely distributed team of folks who don't know each other well and that may work different hours and number of hours may prefer the second approach which gives more control to a central authority.

ContentLicense: CC BY-SA 4.0


答:
Just for fun, I've had C++ programmers reeling with this little baby:

Why does this run into an infinite loop (and yes it's typed correctly)?

```<code>int x=0;
while (x<3) {
  x = x++;
}
</code>```

It's amazing how many get tripped up. Of course, I can't use it any more after it appeared on Stack Overflow. Mutter... mutter...

(To get the proper answer read the confession and definitely read the comments)

Added bonus question

There is the all-time classic FizzBuzz (as featured in the now-famous Coding Horror article). I've never actually used it in an interview myself, but after chucking it around the development team one lunchtime the results were... um... surprisingly accurate.

Confession

I was caught up on the standard "x++ returns the original value" response. However, the correct answer is that the behaviour is undefined because of sequence points. Nobody ever mentioned sequence points in all the times I used this until I posted it here.

I have been educated and I'd genuinely like to thank all those who have taken the time to comment.

Body:
Just for fun, I've had C++ programmers reeling with this little baby:

Why does this run into an infinite loop (and yes it's typed correctly)?

int x=0;
while (x<3) {
  x = x++;
}

It's amazing how many get tripped up. Of course, I can't use it any more after it appeared on Stack Overflow. Mutter... mutter...

(To get the proper answer read the confession and definitely read the comments)

Added bonus question

There is the all-time classic FizzBuzz (as featured in the now-famous Coding Horror article). I've never actually used it in an interview myself, but after chucking it around the development team one lunchtime the results were... um... surprisingly accurate.

Confession

I was caught up on the standard "x++ returns the original value" response. However, the correct answer is that the behaviour is undefined because of sequence points. Nobody ever mentioned sequence points in all the times I used this until I posted it here.

I have been educated and I'd genuinely like to thank all those who have taken the time to comment.


答:
```<code>class SomeObject {
    public string PropertyA { get;set; }
    public string PropertyB { get;set; }

    public SomeObject WithABC(string value) {
        var clone = MemberwiseClone();
        clone.PropertyA = value;
        clone.PropertyB = value;
        clone.PropertyC = value;
        return this;
    }
}

var copy = original.WithABC("another value");
</code>```

Title: Which one of these would be the better way to implement object copying in c#?

Body:
I would like to be able to copy an object and only change a few values. I have come up with two different ways to do this.

```<code>// OPTION A - create a copy constructor and use property
//            initialization to change values

class SomeObject {
    public string PropertyA { get;set; }
    public string PropertyB { get;set; }

    public SomeObject() { }

    public SomeObject(SomeObject copyFrom) {
        PropertyA = copyFrom.PropertyA;
        PropertyB = copyFrom.PropertyB;
    }
}

var original = new SomeObject() {
    PropertyA = "original value",
    PropertyB = "some other original value",
}
// replace only the values I want to replace
var partialCopy = new SomeObject(original) {
    PropertyA = "some new value different from original",
};

// OPTION B - create an Option<T> type and use that

// used as constructor paramaters
public class Option<T> {

    // used in the case where you want
    // the default value of a type instead
    // of the original value (see usage below)
    public static readonly Default = new Option<T>(default(T));

    public T Value { get; private set; }

    public Option(T value) {
        Value = value;
    }

    public static implicit operator T(Option<T> o) {
        return o.Value;
    }

    public static implicit operator Option<T>(T value) {
        return new Option<T>(value);
    }
}

public class SomeObject {
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }

    public SomeObject() { }

    public SomeObject(SomeObject toCopy,
        Option<string> propertyA = null,
        Option<string> propertyB = null)
    {
        PropertyA = propertyA ?? toCopy.PropertyA;
        PropertyB = propertyB ?? toCopy.PropertyB;
    }
}

var original = new SomeObject() {
    PropertyA = "original value",
    PropertyB = "some other original value",
};
// replace only the values I want to replace
var partialCopy = new SomeObject(original,
    propertyA: "new value");
</code>```

The first implementation has much less code to maintain, but you can't enforce things in the constructor. The second is a bit more complicated due to the Option<T> class but you can, in effect, enforce rules better in a constructor at object creation. Do you think the constructor safety of OPTION B overrides the complexity, making it the better choice. Or should I use the simpler OPTION A due to ease of maintenance?

These are simple data transfer objects. They generally have a lot of properties. I'm trying to avoid creating objects like template, templateB, templateB.2, etc. when I can just copy the current object and change the properties I need. For example, properties A,B, and C need to be set to this value when a particular rule passes. However further in the process, properties D,E, and F will need different values based on other rules. I'm trying to avoid code like the following:

```<code>  // I'm trying to avoid this
  ResponseObject SomeMethod(bool inputA, bool inputB) {
     var myObject = CreateObjectFromTemplateA(); // has same values for A,B,C
     if(inputA) {
         myObject.D = "some value";
         myObject.E = "some value";
         myObject.F = "some value";
     } else if (inputB) {
         myObject.D = "some other value";
         myObject.E = "some other value";
         myObject.F = "some other value";
     }
     return myObject;
  }

  // and do something like this instead
  ResponseObject SomeMethod(bool inputA, bool inputB) {
      var defaultValue = CreateFromTemplateA()
      return inputA ? new ResponseObject(defaultValue) { D = "some value",
                                                         E = "some value",
                                                         F = "some value",},
           : inputB ? new ResponseObject(defaultValue) { D = "some other value",
                                                         E = "some other value",
                                                         F = "some other value",},
                    : defaultValue;
  }

  // in some cases it's as simple as one property change
  // and here is where the first method of property initialization
  // breaks down
  ResponseObject SomeMethod(bool inputA, bool inputB) {
      return new ResponseObject(CreateFromTemplateA()) {
             D = inputA ? "some value"
               : inputB ? "some other value
                        : CreateFromTemplateA(), // a second object created
      };
  }

  // here is where the constructor initialization helps
  ResponseObject SomeMethod(bool inputA, bool inputB) {
      return new ResponseObject(CreateFromTemplateA(), // with this method CreateFromTemplateA() could be a property instead of a method call
          d: inputA ? "someValue"
           : inputB ? "someValue"
                    : null // null here indicates use the property value from CreateFromTemplateA()
      );
  }
</code>```


问:
Developing "real" synchronization
I'm currently writing a email synchronizer application that synchronizes email to a sql server database.

One direction is not a problem: Fetching folders from the server (with its messages) and writing them into my database.

What I'm missing, though, is the "reverse" ability: How can I detect which folders or messages have been deleted on the server (e.g. by another application than mine), but are still present in my database?

How can I create such a "two way" synchronization? I've thought of iterating through my current dataset and trying to find those messages and folders on the server. If they do exist in my database, but not on the server, I'd need to delete these items in my database... But that doesn't appear to be the right way to me.

What is the common approach to do this? This seems to be a rather language-irrelevant task.

答:
You are confused. Synchronizing two different instances of similar data requires knowing which version is correct if there is a discrepancy.

If an email message is on one side and not on the other, how do you know whether you should replay a "delete" on the one side, or an "add" on the one side? If email messages with the same ID differ in their content, which version should be propagated to the other side? Until you find a deterministic way of deciding, you can't program a computer to solve it.

Title: Developing "real" synchronization


答:
The problem with the first approach is that features have to go through the developer's develop branch before they reach the shared repository. This means that if a developer has posted a pull request for a big and important feature that takes lots of discussing, reviews, approvals and changes, it'll clung their's develop branch and they won't be able to post smaller pull requests while waiting on other people actions/decisions related to that big PR.

Essentially - the local develop branch becomes a blocking bottleneck for each developer.

The problem with the second approach is that features are tested after they are merged into the shared repo's develop branch. This means you can have bad code in there that'll ruin the project for everyone until fixed. Also, if you decide to postpone or to abandon a feature because it's too hard to fix or because you can't fix it without ruining the overall design you need to change the shared repo's develop branch's history - which is not a very fun thing to do...

Essentially - the shared(!) develop branch becomes a blocking bottleneck for the entire team(!!).

So - I suggest a third approach, that avoids these problems:

Create new branch for feature.

Implement feature.

Test feature branch.

Create pull request onto develop branch.

Merge pull request.

Confirm that everything works.

Merge develop into master.

That way, the blocking pipe is the feature branch - and since you can have as many as you want it's not a bottleneck.

Title: What is proper order of pull requests and testing?

Body:
We want to setup proper development workflow.
We have two main branches: master(release branch) and develop(working branch).
We want to use pull requests properly.
We see two ways how to do this:

The first one:

Create new branch for feature.

Implement feature.

Merge to develop branch.

Test develop branch.

Confirm that everything works.

Create pull request onto master branch.

Merge pull request.

Steps 4 and 7 can return to step 1.

The second one:

Create new branch for feature.

Implement feature.

Create pull request onto develop branch.

Merge pull request.

Test develop branch.

Confirm that everything works.

Merge develop into master.

Steps 4 and 6 can return to step 1.

Which one is better? Or there is better way that I described?

We have 3 team members: developer, tester and reviewer.


答:
I think there are only two categories of algorithms:

Those who rely on versioning and change logs. Basically "give me all of the changes that happened since version #1354."

Those who perform extensive comparisons of each side's data. This can be done in O(n) if the ordering is the same.

For a client-server problem the former will usually require less bandwidth.

Title: Developing "real" synchronization

Body:
I'm currently writing a email synchronizer application that synchronizes email to a sql server database.

One direction is not a problem: Fetching folders from the server (with its messages) and writing them into my database.

What I'm missing, though, is the "reverse" ability: How can I detect which folders or messages have been deleted on the server (e.g. by another application than mine), but are still present in my database?

How can I create such a "two way" synchronization? I've thought of iterating through my current dataset and trying to find those messages and folders on the server. If they do exist in my database, but not on the server, I'd need to delete these items in my database... But that doesn't appear to be the right way to me.

What is the common approach to do this? This seems to be a rather language-irrelevant task.


答:
I believe I would ask them what else they know, or more likely give them a question in something quite different.

Far too many C++ coders about who have little experience of other languages.  Narrow experience is usually restrictive.


问:
What's the right way to work with a graphic designer?
Recently, we worked with a graphic designer (arranged by the client) to provide the skin for a Django+Bootstrap application we had built. The designer provided a series of static images of the new layout, along with a document describing some technical attributes (font sizes, colours, a few dimensions etc).

It turned out to be incredibly time consuming to implement this. Although the whole site was basically a front page, an index page, and half a dozen detail pages, I spent at least 5 days just implementing the CSS and HTML changes. So I'll go out on a limb and call this The Wrong Way.

My basic approach was:

Compare the static image and current rendering, and notice a difference.

Guess what change would be need in the CSS/HTML

Make that change

Go to step 1.

Some of the particular issues were me not understanding that the design included a change from 8 columns to 12, some images provided in the wrong format (.png's can render differently on different browser/platform combinations), hassles trying to undo Bootstrap's styling, the usual CSS wrestling to achieve pixel perfect rendering etc. And occasionally I had to reorganise the HTML templates to get a certain behaviour.

What's the right way?

答:
I have been develloping HTML/CSS with several designers and as already stated, there is no "silver bullet". The designers I have worked with didn't know much (nothing) about html/css. Some of them had some experience in webdesigning and I must say when they have that knowledge, it always ends up with easier to develop and "better website" especialy when responsiveness an UX is involved.

I guess what some companies looking for a website don't know/ignore is : anybody can say he is a graphic designer/webdevelopper/webdesigner/UI designer with basic knowledge (or even none, yes I have seen that) in either. Whereas "real ones" can go the extra mile and produce maintainable, effective websites. I try to "educate" the client and explain that Webdesigning involves skills that "print only" graphic designers don't have. When this works I usualy send the client towards designers I have already worked with and have a common workflow with.

This said, it often happens for many reasons that you end up building websites with people that have graphic skills and no webdesigning skills. In this situation, the best way I have found to save coding time and not end up with a undevellopable layouts is to be involved in the design process and communicate with the designer and explain what you can/cannot do and what would be simpler/better from your point of view.

Although this can be difficult to organize in some situations, it is capital to explain to the client and the designer that "if you think webdesigning form the bigining of a web project you end up saving time, money and headeachs" and that you will be happy to take part in the designing process to save that time money and headeachs.

This is the worflow I try to follow in most projects :

The designer builds graphic standards if they don't exist (I usualy don't get involved here. I just try to hint the designer towards web compliant fonts ex: google fonts)

Mokup made by the designer. I get involved here and work with the designer to build web compliant layouts (especialy for responsive ones) before the client sees it.

client validates mokup

I code the mokup

The time I have spend communicating and working with the designer is saved during the coding process and this ends up with simpler, more maintainable and neatter code.

This doesn't save you from a happy designer calling you on friday evening with a very pretty mokup that the client has seen and now wants with this sentence : "Hey pall, could you code this for me, deadline is ... yesterday!" Then the whole theory falls apart and if you are looking for work at that moment, you're good for a headeach all week end.

Conclusion :

I don't think this is very different than any code related on not project, the best way to work with other people is to communicate with them.


问:
How often should internal applications be deployed?
In Short:

Should I deploy each fix/feature as I make it, or schedule releases for an internal application?

Some Background:

A few months ago I was hired as our IT's first dedicated developer with the ultimate goal of developing an application to replace a 10 year old internal tool that is used multiple times a day by about 20-30 staff within the office (out of maybe 50-60 in total).  The first months were spent getting to know the application as it exists currently: fixing bugs, adding features from the backlog, and integrating web services we want present in version 2.0.

Staff are right there to let me know when they need a little fix/tweak and when something has gone horribly wrong.  For the latter case, I obviously squash the bug and deploy the application asap.  As we are now ready to begin development of its replacement, my question is around how to handle the small fixes/features that we'll continue to support over this development cycle.

When I came on as the dedicated developer for this, I was able to implement multiple web-services and additional automations to enhance the application rather quickly, and fixes could be done within a day (as opposed to whenever our head of IT had time to take a break from other duties).

The Problem:

My fear is that the expectation is starting to be created that tweaks can be done and pushed out the same day. Even if I can fix a small bug or add a small feature and deploy within an hour that could be perpetuating the habit of walking up to my desk and staff saying "Can we move x to this side of the page by tomorrow?"

The Question:

Assuming these internal applications can be easily deployed, how often should I deploy them?  I've tried to implement release versions (for my own sanity) and am considering a once-a-week max (except for breaking bugs) deployment. Is that appropriate? What are the other constraints on release schedule I should consider?

答:
I strongly suspect that the answer will be entirely dependent on how painful (or painless) it will be to upgrade 30 people to the newer version.

The easier you make it to upgrade, the better off you will be with a rapid release schedule. The more painful it is, the more you will benefit from a regular release schedule.

It's completely up to you.


答: Reading from a stream is a side effect already because the result of functions such as isEOF may return different result after the read than before the read.


答: In computer science, a function or expression is said to have a side effect if, in addition to returning a value, it also modifies some state or has an observable interaction with calling functions or the outside world.  Reading from a file is an observable interaction with the outside world.  It meets the definition of side effect.  Reading the 42nd element from global memory would be a side effect as well unless your array is a constant because it would be an observable interaction with other functions that may modify the array.</p>


答:
Have the delete operation record a deleted flag(or date) rather than actually delete data on the server, so that clients may check if a message has been deleted.  Then have a periodic task that purges data that has been deleted for more than Y days, or track time last synced by all known clients and delete after every client that might be interested in a deleted message has synced.  </p>

<p>The other way to do it is to act like version control keep current state + a record changes, and delete is just another change.  Then when a client syncs it says give me all changes since this rev.  </p>

Title: Developing "real" synchronization

Body:
Have the delete operation record a deleted flag(or date) rather than actually delete data on the server, so that clients may check if a message has been deleted.  Then have a periodic task that purges data that has been deleted for more than Y days, or track time last synced by all known clients and delete after every client that might be interested in a deleted message has synced.

The other way to do it is to act like version control keep current state + a record changes, and delete is just another change.  Then when a client syncs it says give me all changes since this rev.


答:
In the world of commercial software, release schedules are tied to:

Development timeline (How long does it take to create each release or patch?)

Testing and QA timeline (How long does it take to test, qualify, and certify the app as running properly on all the platforms and in all the modes in which it will typically be used; this often includes "integration," "stress," and "acceptance" testing, not just unit tests)

Sales and marketing cycles (How long does it take to create demand for, or acceptance of, the new release?)

Customer update cycles (How often do customers want new releases? And at what point in their business cycles can they accept new releases/features? Retailers, e.g., lock down all non-urgent upgrades throughout the entire multi-month "Christmas season")

Training and support integration (How long does it take to document new features/fixes, train both internal and end-users on them, and get your support team up to speed on the changes?)

Traditionally releases are a Big Deal, for both the software developer and the customers. So release cycles of 1-3 years between "major" releases have been common, with "minor" or "dot" releases every 3-6 months, and emergency patches on an as-needed basis.

Cloud and SaaS (software as a service) shops are the opposite extreme, they often "slipstream" updates without ever telling anyone (maybe their support staff, but not always even then). I know shops that do updates once a week, on a fixed day. Others update as often as several times daily.

You're a small shop with an internal app, so there's no real sales/marketing cycle. There doesn't seem to be any official support or testing/QA function between users and development. Your development cycles seem short, and your deployments easy. So you could iterate as fast as your user community will let you.

Having been in this situation, some suggestions:

Just because you don't have an official testing/QA organization doesn't mean you should avoid testing. Please, please, please have an automated testing suite that you run before every release. This can save you a world of hurt later.

Just because you can silently "slipstream" new functions or patches doesn't mean you should. In fact, you should not. Have a real version or release number on EVERY release. This will make tracking down bugs easier. (See e.g. semantic versioning for insight on a structured way to assign release numbers.)

Have an app web page or "about this app" screen that shows recent version updates. Showing users what is "new and notable" is one of the things fast-updated open source projects have learned helps increase user trust and comfort with the update process.

Title: How often should internal applications be deployed?

Body:
In Short:

Should I deploy each fix/feature as I make it, or schedule releases for an internal application?

Some Background:

A few months ago I was hired as our IT's first dedicated developer with the ultimate goal of developing an application to replace a 10 year old internal tool that is used multiple times a day by about 20-30 staff within the office (out of maybe 50-60 in total).  The first months were spent getting to know the application as it exists currently: fixing bugs, adding features from the backlog, and integrating web services we want present in version 2.0.

Staff are right there to let me know when they need a little fix/tweak and when something has gone horribly wrong.  For the latter case, I obviously squash the bug and deploy the application asap.  As we are now ready to begin development of its replacement, my question is around how to handle the small fixes/features that we'll continue to support over this development cycle.

When I came on as the dedicated developer for this, I was able to implement multiple web-services and additional automations to enhance the application rather quickly, and fixes could be done within a day (as opposed to whenever our head of IT had time to take a break from other duties).

The Problem:

My fear is that the expectation is starting to be created that tweaks can be done and pushed out the same day. Even if I can fix a small bug or add a small feature and deploy within an hour that could be perpetuating the habit of walking up to my desk and staff saying "Can we move x to this side of the page by tomorrow?"

The Question:

Assuming these internal applications can be easily deployed, how often should I deploy them?  I've tried to implement release versions (for my own sanity) and am considering a once-a-week max (except for breaking bugs) deployment. Is that appropriate? What are the other constraints on release schedule I should consider?


答:
You are asking the wrong question.

»How often should internal applications be deployed« has many implications which are disadvantageous - e.g. if you have a release-cycle - say 1 week - there are perhaps small but important changes, which have to wait 6.x days to the next release.

It would be a better practice to release as often as you have something to release: which could sometimes be once every two days or twice a day; depending on your workflow. If you have features, which aren't tested enough, you could implement feature-toggles (e.g. configuration values in a DB which de-/activates features). So you could easily roll out to production. And if you realize, that the new feature doesn't behave the way you wanted, you could roll back as fast as you toggle the featureswitch.

My fear is that the expectation is starting to be created that tweaks can be done and pushed out the same day.

Why should that be a problem?
If you can do the fix, why wait to release it?

Even if I can fix a small bug or add a small feature and deploy within an hour that could be perpetuating the habit of walking up to my desk and staff saying "Can we move x to this side of the page by tomorrow?"

Same question: Why is that a problem?

The only problem you have is communication.
You have to earn credibility: If you say, it could be fixed within 10 Minutes and you push it to production in 10 minutes everything will be fine. But on the other hand, if you say it takes 5 days, you should have so much credibility, that everyone knows, that it takes 5 days. You are in charge, you set the deadlines. And you are responsible to communicate that.
This is oftentimes a painful process for both sides - but in the end: both sides win.
As a professional, you have to communicate, how long something takes. Management doesn't write software, users do not write software, you write software.

What can I expect to see as I continue in my career in terms of internal applications? Are there best practices for deployment of internal tools? Are they treated any differently?

I can not foresee, where you are going. But in some parts of the industry, what I described vaguely is known as a process called continous deployment and gains more and more attention.


问:
Grouping multiple Git repositories that are part of the same overall project
Let's say I have a project that has multiple components: a server component, a web app component, an iOS component, an Android component, etc.  These components are all separate codebases, but are also loosely coupled (eg. a change to the server code could require a change to all other components too)

What is the most efficient way in Git to organize this project? If you put it all in one repository, you would always have the latest versions but things become quite messy when you start changing one component and not the others.

On the other hand, if you make each component as a separate repository, how would you be able to "link" these repositories so that you would know that version 2.0 of the app requires version 1.5 of the server component, etc?

Is there a feature in git outside of keeping up to date readmes(or some better solution I don't see) to more effectively manage multiple, related repos?

答:
If you use C#, you can use NuGet.

Make each component a library and keep them in their own repository. Make releases of the basic components that you version according to semantic versioning.

Finally, get your buildserver to package the libraries into NuGet packages, and consume those NuGet packages in the projects for the front-end components (iOS, Android).

The same basic approach (version and package dependencies) can be used in other languages as well, but might not be as convenient.

I would not recommend you to use Git Submodules. While it can be used for these kind of issues in theory, I feel it's a bigger hassle than it's worth.