## What is a good Object-Oriented design for geometry objects when building libraries dealing with geometry operations?

I am trying to design an object-oriented library to handle geometric calculations. However, I am trying to exaggerate on being “tightly” object-oriented and applying relevant “best practices”. I know that there is no reason to be dogmatic about patterns, I am just trying to squeeze out every bit of possibility that I have not found out any different way for what I am about to ask.

Consider trying to design a path, composed of segments. I consider having a common interface for segments, which offers a method to calculate points of intersection with another segment. In short, the tentative signature of such a method might look like:

abstract class Segment {     ...      Point[] Intersection(Segment other);      ... } 

However, when implementing such a method, it might be necessary to check what actual implementation lies behind the “other” Segment. This can be done through run-time type checks, given that the language supports it, otherwise, I have to use some kind of enum to differentiate between segments and, potentially, cast the object to call corresponding methods. In any case, I cannot “extract” some common interface for this kind of design.

I have considered “forcingly” establishing a base-assumption that all path segments boil down to sequences of points, and unify the algorithmic intersection process as being always a line-to-line intersection between all sub-segments, but this will rob the design of a very significant (in my opinion) optimization possibility. Considering the ubiquity and “temporal density” of geometry-based operations the library will be built to support, it is very important, in terms of performance, to take advantage of special shapes having “closed forms” to calculate intersections between them (such as a circular arc with a line), instead of testing a multitude of small line-segment pairs to identify intersection points.

Apart from that, if I make the simplifying assumption of paths consisting of path sequences, I will have to make another relatively pervasive (for such a library) design choice, that of point density, to trace, for example, the various segment types. This would be, in my opinion, a reasonably architecturally-relevant parameter when considering an end result of drawing, e.g. on-screen, in order to achieve a given level of smoothness, for example. However, I feel this is, conceptually” an unsuitable abstraction for the geometric operations between pure geometric abstractions. A circle is not a series of line segments and should not need 5,10 or 100 coordinate pairs to be represented. It is just a center and a radius.

My question is, is there any other way to be object-oriented when dealing with base classes for geometry entities, or the “usual” way of doing things is with an enumeration and implementations checking segment type and exploiting specific geometric relations to potentially optimize the procedures?

The reason I am giving so much thought on this is that I might find myself having to implement special segment types, such as, for example, parametric curves, in the future, or simply allow extension of the API outside of the API itself. If I use the enum-based, type-checked everything-with-everything intersection tests (and do so also for other spatial operations between segments besides intersection), “outsider” extensions of the API will have to “register” themselves in the segment-types enumeration, which would necessitate either changing and rebuilding the original API, or providing a mechanism for external registrations. Or simply make a true global capture of all possible segment geometric forms to account for everything.

To make it simple, assume that I implement this only with segments, and then I add a new implementation of a circular arc. I can “teach” the circular arc how to intersect itself with straight line segments (by checking the segment type for “line”, for example), but I can not “teach” the line segment how to intersect itself with arcs without going back to change the original library.

I understand that there are methods or techniques to provide all this flexibility (I could make segments register special “injected” intersection methods for specific identifiers, which would be determined by the external API extension objects, so that lines will first check whether the object they intersect with is such a “special” type, or simply make intersection methods virtual, so that the developer trying to extend my API will be able to manually “teach” all existing segment implementations how to intersect themselves with my original objects). All I am asking is, is there any other elegant way to tackle this situation?

The top-voted answer to this question suggests excluding the method entirely and delegating it to a different class. This does sound somewhat counter-intuitive, given that segments do know their geometries. However, segments do not know other segments’ geometries, so it appears to be reasonable design decision to “outsource” the intersection method, one that still necessitates knowing the segment type at run-time, however. Since I am trying to represent segments as interfaces “ignorant” of the underlying type (as in “I want to support the use of the segment interface as being ignorant of the underlying implementation”). Apart from that, I would not resort to empty marker interfaces to differentiate between classes. An external “intersector”-like class would look interesting, though I would avoid making it static, in order to allow for extensions and potential changes of strategy (different implementations, optimizing for speed, employing snapping, etc).

## As a DM, how to avoid unconscious metagaming when dealing with a high AC character?

In my previous campaign, a player started the campaign with a tanky fighter build with a chain mail, a shield, and Defense fighting style, for a total of 19 starting AC. For a level 1.

I was still learning to DM, so I became frustrated whenever it was a monster’s turn and the closest target was him. Unconsciously, I finished the monster’s turn noticeably more quickly than others attacking other targets (“Oh, a 12. The dagger can’t pierce your armor. Okay, next one is …”)

This resulted in:

1. Frustration when forced to deal with him – closest target or the only target.
2. Preference on attacking targets other than him, if possible.
3. Preference to attack with save-based effects on him. Usually I saved limited resources of save-based effects and exclusively used them on the tank.

I tried to become as objective as possible, and this resulted in me trying to do the reverse: forcing my monsters to be inefficient by attacking him over easier-to-hit target beside him, reluctant to use save-based effects on him, etc.

I tried to be fair, but it seems I become meta-metagaming and I don’t like that.

How to deal with this tank fairly? I’ve tried not to think about the 19 AC, but it is inevitable that I need that info to properly play the game (and the AC won’t likely to change for a long time).

## Dealing with interrupt and sleep

I was thinking that I could calmly Thread.sleep() on an interrupted thread. Sonar doesn’t think so, of course.

In some circumstates we should waiting for conditions, even if an interrupt occured. Is there anything wrong, for example, with the code below? Is there any better solution?

private void waitFinish() {     boolean wasInterrupted = false;     while (asyncProgressCounter.get() > 0) {         try {             Thread.sleep(100);         } catch (InterruptedException e) { // NOSONAR             wasInterrupted = true;         }     }     if (wasInterrupted) {         Thread.currentThread().interrupt();     }     onFinish(); } 

## Dealing with API errors

I’m building a shop system which works in three parts: a mobile app (Android/iOS) which is used by customers to make orders, view products and so on, a desktop application, used by the managers to manage orders and shop things and a web server with an API to which both mobile and desktop applications communicate.

The server API is restful, but I’m starting to encounter a few problems: if the user tries to buy items that are no longer available, I can’t just send them a BadRequest back and say “Couldn’t complete the order, please try again”, I have to tell them why and tell them which product in the cart is unavailable, so the mobile app knows which product to remove from the cart. That have been fixed by using Dtos everywhere, but other problems began to arise: if the user tries to add a delivery address and some field isn’t valid, I can’t send them a BadRequest with some string message, I have to tell them exactly which field isn’t valid.

So I thought about creating enums with every possible error for every endpoint, but I can’t think of an organized way of doing it. I already have all the possible Dtos for every endpoint, so should I put the enums for each endpoint inside the Dtos? Or another folder/namespace only for it and place every enum inside a corresponding class for the endpoint? I don’t think a single static class for it would be a good approach.

## I am Implementing Static Methods for Dealing with Conversions from and to UTC – Is this Unnecessary?

I asked this question over at stackoverflow but was told it may be better suited here. Many thanks.

So I absolutely want to store DateTimeOffset objects in UTC format. To achieve the correct conversions, I’ve created my own methods to deal with the conversions.

/// <summary>String representation of the specified time zone.</summary>         private const String LOCAL_TIME_ZONE_STRING_REPRESENTATION = "GMT Standard Time";         /// <summary>TimeZoneInfo representation of the specified time zone.</summary>         private static TimeZoneInfo LOCAL_TIME_ZONE = TimeZoneInfo.FindSystemTimeZoneById(LOCAL_TIME_ZONE_STRING_REPRESENTATION);          /// <summary>With a given DateTime, passed DateTime is assumed it has been parsed and shares the same time zone as TimeZoneInfo LOCAL_TIME_ZONE.</summary>         /// <param name="dateAndTime">DateTime in TimeZoneInfo LOCAL_TIME_ZONE.</param>         /// <returns>UTC DateTime.</returns>         public static DateTime ConvertToUtcDateTime(DateTime dateAndTime)         {             return TimeZoneInfo.ConvertTime(dateAndTime, LOCAL_TIME_ZONE).ToUniversalTime();         }         /// <summary>With a given DateTime, the DateTime is assumed to be a UTC time. It will then return a DateTime converted to TimeZoneInfo LOCAL_TIME_ZONE.</summary>         /// <param name="dateAndTime">DateTime that is in UTC.</param>         /// <returns>Converted to TimeZoneInfo LOCAL_TIME_ZONE DateTime.</returns>         public static DateTime ConvertToLocalDateTime(DateTime dateAndTime)         {             return TimeZoneInfo.ConvertTimeFromUtc(dateAndTime, LOCAL_TIME_ZONE);         } 

Using the String constant LOCAL_TIME_ZONE_STRING_REPRESENTATION, any user who wishes to compile the code can specify which time zone they want the code to run in, rather than it try to use Window’s local time zone.

Then the two above methods can be used to make a conversion between between the two:

private static void Main()         {             //Parse a date and time. It is to be assumed this parsed date and time is in the same time zone             // as LOCAL_TIME_ZONE.             DateTimeOffset dateTime = ConvertToUtcDateTime(new DateTime(2019,6,1,15,30,0));              //Assuming we have retrieved a date and time that is in UTC time, we can now convert it             // to the same time zone as LOCAL_TIME_ZONE.             DateTime convertedFromUTC = ConvertToLocalDateTime(dateTime.DateTime); } 

The system would be able to parse DateTime’s that have no time zone associated with them regardless where they would’ve came from, and convert them into UTC time assuming that DateTime came from the same TimeZone as LOCAL_TIME_ZONE. The only time where we would need to convert retrieved UTC DateTimes back into the same time zone as LOCAL_TIME_ZONE would be when we are visually displaying it to a user. All TimeSpan calculations etc, would use the UTC DateTimeOffset.

This seems to work as intended, and I can change LOCAL_TIME_ZONE_STRING_REPRESENTATION to any time zone I want, and using the methods I created, the system uses that time zone instead of Window’s local time zone.

This would be particularly useful for me as the server hosting an application may be in a different time zone and have a different culture, but its intended users could be for a totally different time zone.

Am I making too much work for myself, or would this be a reasonable way to implement what I need?

## Riccati equations for dealing with stiffness of ODEs

Early texts [Forman Acton, Numerical Methods that Work; Numerical Recipes, first edition] suggested that for integrating a stiff linear ODE it was very helpful to integrate the associated Riccati equation instead. This point was made specifically for using shooting methods, i.e. algorithms that use an initial value method to solve a boundary value problem. I have not seen any followup on this point in the literature — the statement does not appear in later editions of Numerical Recipes, for instance — and I’m wondering whether this Riccati methodology is no longer considered a useful way to deal with stiffness.

## Probability Question Dealing With Multiple Choice Questions

A students is taking a multiple choice test where each question has 5 possible answers, only one of which is correct. If the student knows the answer he selects the correct answer, otherwise he selects his answer choice randomly. The student knows the answer to $$70$$% of the questions.

i) What is the probability that on a given question, the student gets the correct answer?

My thought was that I could use conditional probability:

$$\dfrac{(0.2)(0.7)}{0.2}$$

But then thought maybe that would not be appropriate, and a made a tree diagram and came up with an answer of $$0.76$$. This takes into account, I believe, the cases where he does not know the answer but guesses correctly.

Any thoughts?

## Magento 2 console script dealing with area code not set / area code already set error

I’ve written a console for invoicing frontend orders

https://github.com/DominicWatts/Magento2-AutoInvoice/blob/master/app/code/Xigen/AutoInvoice/Console/Command/Invoice.php

If I put Magento\Sales\Model\Service\InvoiceService in the constructor and run setup:di:compile magento console throws an ‘Area Code Not Set’ error.

You can’t set area code as part of the constructor because when you run this and other console commands you see ‘Area Code Already Set’ error.

I understand state and why setting the ‘area’ is necessary.

My workaround is to do the following

use Magento\Sales\Model\Service\InvoiceService;   protected function execute(InputInterface $input, OutputInterface$  output) {     $this->state->setAreaCode(\Magento\Framework\App\Area::AREA_GLOBAL);$  this->method(); } public function method() {     $this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();$  this->invoiceService = \$  this->_objectManager->create(InvoiceService::class);     // do stuff } 

So basically using object manager at runtime instead of injecting. I’m constantly reading that using the object manager is bad. Therefore I feel like I’m not understanding a key concept.

So my questions are this:

a) Is this the right way to work around the issue?

b) If it’s not – what is the correct approach?

c) Does using object manager add resource overhead? Or is it more that it will be deprecated at some stage.

## A problem Dealing with Sampling with replacement

Below is a problem from the Schaum book: “Probability and Statistics”. I started the problem but I am confident that I am on the wrong approach. I am hoping somebody will tell me where I went wrong.
Problem:
An urn holds $$60$$ red marbles and $$40$$ white marbles. Two sets of $$30$$ marbles are drawn with replacement from the urn, and their color is noted. What is the probability that the two sets differ by $$8$$ or more red marbles.
First we note that both sets should have a mean of $$0.4*30 = 7.5$$ white marbles. Let $$X$$ be a random variable whose value is $$1$$ if on a single draw the marble is red and $$0$$ if the marble is white. \begin{align*} u_x &= \frac{3}{5} \ \sigma_x^2 &= E(X^2) – u_x^2 \ E(X^2) &= \frac{3}{5} \ \sigma_x^2 &= \frac{3}{5} – \left( \frac{3}{5} \right)^2 = \frac{15}{25} – \frac{9}{25} \ \sigma_x^2 &= \frac{6}{25} \ \sigma_s^2 &= \frac{\sigma_x^2}{n} \ n &= 30 \ \sigma_s^2 &= \frac{\frac{6}{25}}{30} = \frac{3}{25(15)} \ \sigma_s^2 &= \frac{1}{125} \ \sigma_s &= \frac{1}{5\sqrt{5}} \ \end{align*} The book’s answer to the problem is $$0.0482$$ and I am confident that my work is wrong. Please tell me where I went wrong.