## design patterns – Java: class inheritance and generic types

I’m currently working on inheritance in Java. I would like to discuss the following case with you.

In my example, I have numerous animal and enclosure classes. All animals are derived from BaseAnimal. All enclosure are derived from BaseEnclosure. Both base classes provide various concrete methods – but also some abstract methods.

Now, when implementing a CatEnclosure, I want to specify that when CatEnclosure.resettleTo(Enclosure) is called, only one Cat Enclosure can be passed. In my current code, a cat could also be placed with a dog.

To my understanding, I would have to define the class of the future (derived) class when creating the abstract method resettleTo in the BaseEnclosure class.

My idea was to use a second generic. So BaseEnclosure becomes BaseEnclosure <E, A>. But now I would also have to specify that E must be derived from BaseEnclosure. In addition, of course, A should also be of the BaseAnimal type.

So I get: BaseEnclosure <E extends BaseEnclosure, A extends BaseAnimal>

My IDE now complains that BaseEnclosure and BaseAnimal are raw types. If I write BaseEnclosure <E extends BaseEnclosure , A extends BaseAnimal <?,? >>, it works. However, I don’t know whether all of this makes sense in terms of design.

I look forward to your suggestions.

Enclosed you get the example code.

``````public abstract class BaseAnimal<E> {
protected E enclosure;

public void setEnclosure(E enclosure) {
this.enclosure = enclosure;
}

public E getEnclosure() {
return enclosure;
}

public abstract String getNoise();
}
``````
``````public abstract class BaseEnclosure<A> {
protected List<A> animals = new ArrayList<A>();

// some methods...

public List<A> getAnimals() {
return animals;
}

public abstract void resettleTo(BaseEnclosure other);
}
``````
``````public class Cat extends BaseAnimal<CatEnclosure> {

@Override
public String getNoise() {
return "miiiaaauu";
}
}
``````
``````public class CatEnclosure extends BaseEnclosure<Cat>{

@Override
public void resettleTo(BaseEnclosure other) {
// hm...
}
}
``````
``````public class Dog extends BaseAnimal<DogEnclosure> {

@Override
public String getNoise() {
return "wuff";
}
}
``````
``````public class DogEnclosure extends BaseEnclosure<Dog>{

// some methods...

@Override
public void resettleTo(BaseEnclosure other) {
// hm...
}
}
``````
``````public class Main {

public static void main(String() args) {
DogEnclosure doghouse = new DogEnclosure();
Dog dog = new Dog();
// later: JPA
dog.setEnclosure(doghouse);

CatEnclosure catbox = new CatEnclosure();
Cat cat = new Cat();
// later: JPA
cat.setEnclosure(catbox);

// OHOHOH!!!
doghouse.resettleTo(catbox);
}
}
$$```$$
``````

## php – Hide class if another class is empty

I want to hide the contract class if the person_name is empty. SO that read more doesn’t appear in the director’s image box. Please help.

Here is the code.

r”;
\$opn=1;
}
\$image = wp_get_attachment_image_src(\$image_id, ‘medium’);
echo “ttttt“.\$row(‘person_name’).”“.\$row(‘person_title’).”

“.\$row(‘person_bio’).”

\$cnt++;
if(\$cnt % 4 == 0){
echo “tttt”;
\$opn=0;
}
endforeach;
if(\$opn==1) echo “tttt”;
?>

## c++ – Templated Fraction Class and programming design

Story

I was trying to solve a hard problem from Project Euler earlier today (continued from yesterday) and I wanted to graph some things up and play a little bit with fractions. To work with fractions, I decided to implement a little OOP-ish fraction class. I was hoping to brush up whatever little knowledge of C++ I have into trying and implementing a full blown templated project (as I don’t practice software design very often and am relatively on the newer side of programming (1.8-ish years)). After fixing what seems like a million template errors (we all can agree on how terrible compilers are with reporting template errors), the following code is what I’ve arrived at in one day’s work.

Code

``````/**
Lost Arrow (Aryan V S)
Monday 2020-10-19
**/

#ifndef FRACTION_H_INCLUDED
#define FRACTION_H_INCLUDED

#include <algorithm>
#include <stdexcept>
#include <type_traits>
#include <utility>

/**
* The fraction class is meant to represent and allow usage of fractions from math.
* It is represented by a numerator and a denominator (private context).
* The interface provides you with simple operations:
*      - Construction/Assignment
*      - Comparison (equality/inequality, less/greater than, lesser/greater equal to, three-way (C++20 spaceship operator))
*      - Conversion (bool, decimal)
*      - I/O Utility
*      - Access/Modification
*/

template <typename T>
class fraction {
/**
* fraction <T> is implemented to work only with T = (integer types)
* using floating point or any other types in fractions doesn't make sense.
*/
static_assert(std::is_integral <T>::value, "fraction requires integral types");

public:

/**
* Constructors
*/
fraction ();
fraction (const T&, const T&);
fraction (T&&, T&&);
fraction (const fraction&);
fraction (fraction&&);
fraction (const std::pair <T, T>&);
fraction (std::pair <T, T>&&);

/**
* Access/Modification
*/
T  nr () const;
T  dr () const;
T& nr ();
T& dr ();
std::pair <T, T>   value () const;
std::pair <T&, T&> value ();

/**
* Utility
*/
void print (std::ostream& = std::cout) const;

template <typename S>
S decimal_value () const;
std::pair <T, T>   operator () () const;
std::pair <T&, T&> operator () ();
operator bool() const;

/**
* Comparison
*/
int8_t spaceship_operator (const fraction <T>&) const;
template <typename S>
friend bool operator == (const fraction <S>&, const fraction <S>&);
template <typename S>
friend bool operator != (const fraction <S>&, const fraction <S>&);
template <typename S>
friend bool operator <= (const fraction <S>&, const fraction <S>&);
template <typename S>
friend bool operator >= (const fraction <S>&, const fraction <S>&);
template <typename S>
friend bool operator <  (const fraction <S>&, const fraction <S>&);
template <typename S>
friend bool operator >  (const fraction <S>&, const fraction <S>&);

/**
* Arithmetic
*/
fraction <T>& operator += (const fraction <T>&);
fraction <T>& operator -= (const fraction <T>&);
fraction <T>& operator *= (const fraction <T>&);
fraction <T>& operator /= (const fraction <T>&);

private:
mutable T m_nr, m_dr;

/**
* Utility
*/
void normalize () const;
};

/** ::normalize
* The normalize utility function converts a fraction into its mathematically equivalent
* "simplest" form.
* The functions throws a domain error if the denominator is ever set to 0.
*/
template <typename T>
inline void fraction <T>::normalize () const {
if (m_dr == 0)
throw std::domain_error("denominator must not be zero");
T gcd = std::gcd(nr(), dr());
m_nr /= gcd;
m_dr /= gcd;
}

/** ::spaceship_operator
* The spaceship operator provides similar functionality as the <=> operator introduced in C++20.
* If self  < other : return value is -1
* If self == other : return value is  0
* If self  > other : return value is  1
*/
template <typename T>
inline int8_t fraction <T>::spaceship_operator (const fraction <T>& other) const {
normalize();
other.normalize();

if ((*this)() == other())
return 0;

if (nr() * other.dr() < other.nr() * dr())
return -1;

return 1;
}

/**
* Constructors
*/
template <typename T>
fraction <T>::fraction ()
: m_nr (0)
, m_dr (1)
{ }

template <typename T>
fraction <T>::fraction (const T& nr, const T& dr)
: m_nr (nr)
, m_dr (dr)
{ normalize(); }

template <typename T>
fraction <T>::fraction (T&& nr, T&& dr)
: m_nr (std::move(nr))
, m_dr (std::move(dr))
{ normalize(); }

template <typename T>
fraction <T>::fraction (const fraction <T>& other)
: fraction (other.nr(), other.dr())
{ }

template <typename T>
fraction <T>::fraction (fraction <T>&& other)
: fraction (std::move(other.nr()), std::move(other.dr()))
{ }

template <typename T>
fraction <T>::fraction (const std::pair <T, T>& other)
: fraction (other.first, other.second)
{ }

template <typename T>
fraction <T>::fraction (std::pair <T, T>&& other)
: fraction (std::move(other.first), std::move(other.second))
{ }

/** ::nr
* An accessor function that returns a copy of the numerator value to the caller.
*/
template <typename T>
inline T fraction <T>::nr () const {
return m_nr;
}

/** ::dr
* An accessor function that returns a copy of the denominator value to the caller.
*/
template <typename T>
inline T fraction <T>::dr () const {
return m_dr;
}

/** ::nr
* An modification function that returns a reference of the numerator value to the caller.
*/
template <typename T>
inline T& fraction <T>::nr () {
return m_nr;
}

/** ::dr
* An modification function that returns a reference of the denominator value to the caller.
*/
template <typename T>
inline T& fraction <T>::dr () {
return m_dr;
}

/** ::print
* An utility function that prints to the standard output stream parameter in the form: nr/dr
*/
template <typename T>
inline void fraction <T>::print (std::ostream& stream) const {
normalize();
stream << nr() << "/" << dr();
}

* An utility function that reads from the standard input stream in the form: nr dr
*/
template <typename T>
inline void fraction <T>::read (std::istream& stream) {
stream >> nr() >> dr();
normalize();
}

/** ::decimal_value
* An utility function that converts a fraction to its mathematically equivalent floating point representation
* This function requires its template type as a floating point type.
*/
template <typename T>
template <typename S>
inline S fraction <T>::decimal_value () const {
static_assert(std::is_floating_point <S>::value, "decimal notation requires floating point type");
normalize();
return static_cast <S> (nr()) / static_cast <S> (dr());
}

/** ::value
* An utility function that returns a standard pair with the copy of the numerator and denominator to the caller.
*/
template <typename T>
inline std::pair <T, T> fraction <T>::value () const {
return std::pair <T, T> (nr(), dr());
}

/** ::value
* An utility function that returns a standard pair with a refernce to the numerator and denominator to the caller.
*/
template <typename T>
inline std::pair <T&, T&> fraction <T>::value () {
return std::pair <T&, T&> (nr(), dr());
}

/** ::operator ()
* Provides same functionality as ::value with copy.
*/
template <typename T>
inline std::pair <T, T> fraction <T>::operator () () const {
return value();
}

/** ::operator ()
* Provides same functionality as ::value with reference.
*/
template <typename T>
inline std::pair <T&, T&> fraction <T>::operator () () {
return std::pair <T&, T&> (nr(), dr());
}

/** ::bool()
* Converts a fraction to a boolean value which is false if the numerator is 0.
*/
template <typename T>
inline fraction <T>::operator bool() const {
return bool(nr());
}

/**
* Comparison (implemented with the spaceship_operator
*/
template <typename S>
inline bool operator == (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) == 0;
}

template <typename S>
inline bool operator != (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) != 0;
}

template <typename S>
inline bool operator <= (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) <= 0;
}

template <typename S>
inline bool operator >= (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) >= 0;
}

template <typename S>
inline bool operator < (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) == -1;
}

template <typename S>
inline bool operator > (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) == 1;
}

/**
* Arithmetic
*/
template <typename T>
fraction <T>& fraction <T>::operator += (const fraction <T>& other) {
normalize();
other.normalize();
T lcm = std::lcm(dr(), other.dr());
nr() = nr() * (lcm / dr()) + other.nr() * (lcm / other.dr());
dr() = lcm;
normalize();
return *this;
}

template <typename T>
fraction <T>& fraction <T>::operator -= (const fraction <T>& other) {
return *this += fraction <T> (-other.nr(), other.dr());
}

template <typename T>
fraction <T>& fraction <T>::operator *= (const fraction <T>& other) {
normalize();
other.normalize();
nr() *= other.nr();
dr() *= other.dr();
normalize();
return *this;
}

template <typename T>
fraction <T>& fraction <T>::operator /= (const fraction <T>& other) {
return *this *= fraction <T> (other.dr(), other.nr());
}

template <typename T>
fraction <T> operator + (fraction <T>& left, fraction <T>& right) {
fraction <T> result (left);
return result += right;
}

template <typename T>
fraction <T> operator - (fraction <T>& left, fraction <T>& right) {
fraction <T> result (left);
return result -= right;
}

template <typename T>
fraction <T> operator * (fraction <T>& left, fraction <T>& right) {
fraction <T> result (left);
return result *= right;
}

template <typename T>
fraction <T> operator / (fraction <T>& left, fraction <T>& right) {
fraction <T> result (left);
return result /= right;
}

#endif // FRACTION_H_INCLUDED
``````

Questions and other stuff

According to modern programming standards in C++, how well is my code written? According to software engineering standards, what are the areas I need to improve in? Is my code efficient and well written? Are there any ways I could speed up some computations for efficiency? What improvements to the interface are possible? What could I clean up or refactor in my code? Other relevant insights and tips/discussion/reviews will be appreciated.

To make my implementation more efficient, I’m thinking that I have `normalize()` at a lot of places which runs in `O(log(a.b))` and I could add another private variable which checks if a fraction has been normalized or not. This could get rid of redundant runs on normalize. Any other suggestions will be warmly welcomed.

Please don’t mind the terrible documentation. I would really do that part much better if my goal was to write a fraction implementation for the sake of writing a fraction implementation and not for solving some problem, and if I were to not have to finish it in one days work. Also, any comments on a good procedure to document stuff are welcome (I know this is subjective and different people have different answers to this but something like a short 101 will likely provide helpful info for future projects).

Thanks SE Community!

I am trying to build a login/register script with php but i keep getting the ‘Class Not Found’ error while try to include extended class in my session.php file. Could you please tell me where am i doing wrong?

This is my session.php file:

``````<?php

session_start();
require_once 'auth.php';
\$cuser = new Auth();

if (!isset(\$_SESSION('user'))) {
header('location:index.php'); // Redirect To User If User Is Not Logged In
die;
}

\$cemail = \$_SESSION(('user'));

\$data = \$cuser->currentUser(\$cemail);
``````

This is my auth.php file:

``````<?php

require_once 'databese.php';

class Auth extends Database
{
// BEGIN: New User Registiration //
{
\$sql  = "INSERT INTO users (name, email, password) VALUES (:name, :email, :pass)";
\$stmt = \$this->conn->prepare(\$sql);
\$stmt->execute(('name' => \$name, 'email' => \$email, 'pass' => \$password));

return true;
}
// END: New User Registiration //
// BEGIN: Checking If The User Already Exist In Database //
public function user_exist(\$email)
{
\$sql  = "SELECT email FROM users WHERE email = :email";
\$stmt = \$this->conn->prepare(\$sql);
\$stmt->execute(('email' => \$email));
\$result = \$stmt->fetch(PDO::FETCH_ASSOC);

return \$result;
}
// END: Checking If The User Already Exist In Database //
// BEGIN: Logged In Existing User //
{
\$sql  = "SELECT email, password FROM users WHERE email = :email AND deleted !=0";
\$stmt = \$this->conn->prepare(\$sql);
\$stmt->execute(('email' => \$email));
\$row = \$stmt->fetch(PDO::FETCH_ASSOC);

return \$row;
}
// END: Logged In Existing User //
// BEGIN: Logged In Current User //
public function currentUser(\$email)
{
\$sql  = "SELECT * FROM users WHERE email = :email AND deleted != 0";
\$stmt = \$this->conn->prepare(\$sql);
\$stmt->execute(('email' => \$email));
\$row = \$stmt->fetch(PDO::FETCH_ASSOC);

return \$row;
}
// END: Logged In Current User //
}

``````

This is my dashboard.php file:

``````<?php
require_once 'assets/includes/session.php';
define('TITLE', "Dashboard");
?>

<!-- BEGIN: Content-->
<div class="app-content content">
<div class="content-overlay"></div>
<div class="content-wrapper">
<div class="content-body">
<div class="row">
Content
</div>
</div>
</div>
</div>
<!-- END: Content-->

<?php

include 'assets/layouts/footer.php';

?>
``````

And this is the error i am getting:

## pathfinder 1e – Is there any way to gain access to Evasion without taking multiple levels of a class?

So, I have a character with a really, really, really bonkers Reflex save. It wasn’t really the design plan, but a combination of class features, ancillary benefits from traits, and stats meant that I ended up with one.

Given that, Evasion would be a really great feature to have – better still, the Twist Away feat, which requires Evasion, would be incredible for this particular character, and thematically fitting.

Problem is, dipping 2 levels of Rogue (or another class) is a larger setback than I’d like.

So, is there any way to get Evasion through a feat or other means? I’m particularly interested in permanent methods, in order to qualify for other feats. One level dips are worth mentioning, but not ideal, and if it helps any, the character is Mythic, on the Trickster path, and can expect to get to Tier 10 ‘someday’ (but not anytime soon).

I’m interested in solutions that might apply for any race/class/level combination, as it seems a handy thing to pick up in a variety of circumstances – especially since Twist Away exists. That said, my particular circumstance is a Half Elf, Swash 1/Investigator 7 (the ACG versions).

## Getting Bootstrap Carousel to set Active class?

I have a Drupal 7 site that has 2 Bootstrap carousels.

1. One that rotates automatically and takes up the width of the page.
2. One that has 3 smaller items and only when the page is narrowed (e.g. on mobile device) does it need to rotate.

The first carousel works fine.

The second carousel does rotate until I manually add the “Active” to the class. Once I do it then begins to auto-rotate between the items.

``````<div id="carousel-posts" class="carousel slide carousel-posts" data-ride="carousel">
<!-- Carousel items -->
<div class="carousel-inner">
<div class="item ">...</div>
<div class="item ">...</div>
<div class="item active">...</div>
<div class="item ">...</div>
</div>
</div>
``````

I am trying to figure out how to set one of the items as ” active” when the page loads so that if the page is on mobile or resized to small enough it begins to auto-rotate.

I use nodequeue to order the items and bootstrap view to lay them out.

Thank you for any direction you can point me to.

## java – Base Class System for splitting a spigot command in subcommands

Related to this question: Spigot Plugin: Generic form of the plugin’s main clas

I’ve created a Clan-Plugin, in which I have one “main” command, which is simply `/clan`. Then there are several sub-commands, e.g. `/clan leave`, `/clan money`, etc. There are also subcommands that require multiple arguments, like `/clan create`, where you have to provide details about the clan you want to create.

My very basic problem is, that spigot only offers the possibility to implement commands based on the first word, and not the arguments. What you have to do is manually differ between the subcommands, and then execute the code. In the past I did this by having a massive if-elseif-elseif-… construct in the executor method of the command, with the code of the sub-commands being placed in methods. However, that made this class become really massive oover the time, until it hit the 1000 lines recently. I really thought I should refactor the command, so I came up with the following idea (which I successfully implemented).

I created a base class for all subcommands, `AbstractCommand`, and a Child Class (which is still abstract) for sub-commands, that have to be confirmed before being executed (e.g. deletion of the clan) `AbstractConfirmCommand`. Also I wrote a little `CommandRegistry`-Class to store all the implementations of the AbstractCommand, and find the proper one to execute when necessary. Then in my Main class (which can be found in above link, if there is anyone interested), I register all the Implementations of AbstractCommand. My “Spigot-ClanCommand-Class” has now shrunk down to 80 lines, with which I’m quite happy to be honest. However, I’m not experienced at all with abstract classes, and am not even sure if an abstract class was the better choice over an interface. Here’s my code, I hope I could make it clear what it’s supposed to do.

AbstractCommand:

``````import org.bukkit.command.Command;
import org.bukkit.entity.Player;

public abstract class AbstractCommand {

protected final String commandName;

protected AbstractCommand(String commandName) {
this.commandName = commandName;
}

public abstract void execute(Player player, Command cmd, String arg2, String() args);

public String getCommandName() {
return commandName;
}

}
``````

AbstractConfirmCommand:

``````import org.bukkit.command.Command;
import org.bukkit.entity.Player;

import com.clanplugin.manager.MessageManager;

public abstract class AbstractConfirmCommand extends AbstractCommand {

private int requiredPositionOfConfirm = 1;

protected AbstractConfirmCommand(String commandName) {
super(commandName);
}

protected void setConfirmPosition(int position) {
requiredPositionOfConfirm = position;
}

@Override
public void execute(Player player, Command cmd, String arg2, String() args) {
if (args.length < requiredPositionOfConfirm || args.length > requiredPositionOfConfirm + 1) {
return;
}

if (args.length == requiredPositionOfConfirm) {
withoutConfirm(player, cmd, arg2, args);
return;
}

if (args.length == requiredPositionOfConfirm + 1) {
if (args(requiredPositionOfConfirm).equalsIgnoreCase("confirm")) {
withConfirm(player, cmd, arg2, args);
} else {
withoutConfirm(player, cmd, arg2, args);
}
return;
}
}

protected abstract void withoutConfirm(Player player, Command cmd, String arg2, String() args);

protected abstract void withConfirm(Player player, Command cmd, String arg2, String() args);
}
``````

CommandRegistry:

``````import java.util.HashSet;

import org.bukkit.command.Command;
import org.bukkit.entity.Player;

import com.clansystem.manager.MessageManager;

public class CommandRegistry {

private HashSet<AbstractCommand> registeredCommands;

public CommandRegistry() {
registeredCommands = new HashSet<AbstractCommand>();
}

public void registerCommand(AbstractCommand command) {
}

public void executeCommand(Player player, Command cmd, String arg2, String() args) {
for (AbstractCommand registeredCommand : registeredCommands) {
if (registeredCommand.getCommandName().equalsIgnoreCase(args(0))) {
registeredCommand.execute(player, cmd, arg2, args);
return;
}
}
player.sendMessage(MessageManager.getHelpMessage());
}
}

``````

ClanCommand:

``````public class ClanCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String arg2, String() args) {

if (!(sender instanceof Player)) {
sender.sendMessage("Clan-Commands können nur von Spielern ausgeführt werden.");
return true;
}

Player player = (Player) sender;

//Some checks which are irrelevant here... (e.g. command cooldown, permission-check etc)

if (args.length == 0) {
player.sendMessage(MessageManager.getHelpMessage());
return true;
}

Main.getCommandRegistry().executeCommand(player, cmd, arg2, args);

return true;
}
}
``````

Finally, I’ll append an example of an implementation of AbstractCommand:

``````import org.bukkit.command.Command;
import org.bukkit.entity.Player;

import com.clanplugin.commands.AbstractCommand;
import com.clanplugin.manager.MessageManager;
import com.clanplugin.utils.PermissionUtils;

public class ShowMaxClanMemberCommand extends AbstractCommand {

public ShowMaxClanMemberCommand() {
super("maxmember");
}

@Override
public void execute(Player player, Command cmd, String arg2, String() args) {
int limit = PermissionUtils.getTotalClanMembersAllowed(player);

player.sendMessage(MessageManager.getMaxMemberMessage(limit));
}

}

``````

What I want to know is, if the basic idea of creating an abstract class is “good practice”, and how I can improve my construct. Also I’m pretty new to the site, and I’m not sure if this is too much code for one post. If so, please tell me 🙂

## java – Ensuring if an object is Assignable from a class type

I am trying to ensure type in the below method. How to reduce its cognitive complexity to below 15 from the current 27? It looks more readable as it is? Is there a way to break this down to make it more readable?

Shifting some of the checks to separate method will be one way but is there a better way?

``````private Object ensureType(Class<?> expectedClass, Object value) {
if (value == null)
return null;
Class<?> valueClass = value.getClass();
if (expectedClass.isAssignableFrom(valueClass))
return value;

if (expectedClass.isAssignableFrom(String.class)) {
return value.toString();
}
if (expectedClass.isAssignableFrom(Date.class)) {
if (Number.class.isAssignableFrom(valueClass)) {
return new Date(((Number) value).intValue());
}
try {
return formatter.parse(value.toString());
} catch (ParseException e) {
throw new ClassCastException("argument " + value + " of type " + valueClass + " cannot be converted to "
+ expectedClass + ":" + e);
}
}
if (expectedClass.isAssignableFrom(Integer.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).intValue();
return Integer.parseInt(value.toString());
}
if (expectedClass.isAssignableFrom(Double.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).doubleValue();
return Double.parseDouble(value.toString());
}
if (expectedClass.isAssignableFrom(Float.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).floatValue();
return Float.parseFloat(value.toString());
}
if (expectedClass.isAssignableFrom(Short.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).shortValue();
return Short.parseShort(value.toString());
}
if (expectedClass.isAssignableFrom(Byte.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).byteValue();
return Byte.parseByte(value.toString());
}
if (expectedClass.isAssignableFrom(Long.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).longValue();
return Long.parseLong(value.toString());
}
if (expectedClass.isAssignableFrom(Boolean.class)) {
return Boolean.parseBoolean(value.toString());
}

throw new ClassCastException(
"argument " + value + " of type " + valueClass + " cannot be converted to " + expectedClass);
}
``````

PS: I am moving this question from Stackoverflow to CR as it was suggested in the comments.

## software engineering – Game Architecture: Class leaking into almost all files

We currently have the problem that our main class GameController is being pulled into every backend file in our game. We’re wondering what are common solutions to this problem.

Here’s a bit more about the game architecture. The game is a board game, so since ~90-95% of the time there isn’t anything happening, the game is set up more like a rest API. It waits for a user prompt, when received, the msg is distributed to the respective components of the game and the proper logic is executed. No large update loops, just executes logic when prompted.

The problem is that as this msg cascades through the system, GameController acts more like a relay point between the systems. It’s how the nodes communicate to each other so that all game components are updated properly. The problem is that it’s created this system where all new/old classes contain a pointer to parentGame, so GameController is everywhere.

Are there any simple architectural solutions to avoid having every class contain a pointer to parentGame? Is this necessarily a bad thing?

Some example code:

``````class GameController {
bank: Bank
action: Action
...
}
class Bank {
parentGame: GameController

constructor(game: GameController) {
this.parentGame = game
}
}
class Action {
parentGame: GameController

constructor(game: GameController) {
this.parentGame = game
}
}
$$```$$
``````

## dnd 5e – How do I explain to an AD&D player that items that increase Armor Class in D&D 5e are overpowered?

### +2 AC is much more than an 8% improvement, in one case it is as high as 200%.

Erik’s and Quadratic Wizard’s answers do a fine job of comparing the proposed item to existing magical items in the DMG. The trouble is, if I only believe it is an 8% improvement in AC, I’m going to conclude that the DMG is wrong about how strong +2 AC is. So it seems good and necessary to actually correct the notion that +2 AC is only an 8% improvement.

Sure, the number increases from 21 to 23, which is an improvement somewhere between 8-10%. But that is not how we measure the effectiveness of AC or how much it improves when we increase it.

I have constructed the following table. Column 1 shows that hit bonus of the attacking creature. Columns 2 and 3 show the probability of that creature hitting ACs 21 and 23, respectively. Column 4 shows the percentage of attacks that would hit AC 21, but miss AC 23. Finally, column 5 shows the percentage improvement in survivability of the change in AC. Column 5 is how we determine the marginal effectiveness of a change in armor class.

As you can see, even against the mighty Tarrasque (+19 to hit), the improvement is still better than 8%, sitting around 12%. But we aren’t fighting a Tarrasque at level 6. As mentioned in your question, we’re looking more in the range of +4 to +6 to hit, which gives +2 AC an improvement between 50% and 100%, which is quite significant. 50% of +4 to hit attacks that would have hit me before now miss me. In terms of survivability, this doubles my durability. Increasing my AC from 21 to 23 means I can last twice as long (on average) against a creature that has a +4 to hit. That’s a 100% improvement. Not 8%.

### How powerful is AC 23 at 6th level?

It’s pretty powerful. As in, most encounters at this level will pose virtually no risk of harm. But let’s try to set up something of an experiment and run some numbers.

Say our paladin with an AC of 23 is out adventuring solo and gets attacked by three blue dragon wyrmlings.

A blue dragon wyrmling has +5 to hit and deals 1d6+1d10+3 (average 12) damage on a hit. Consulting our table, the blue dragon wyrmling has a 15% chance to hit our paladin with an AC 23. Thus, the average damage sustained by our paladin each round is:

$$3 times 0.15 times 12=5.4$$

A 16 CON paladin taking the average increase for hit points each level will have a modest 58 hit points, which means our paladin can be expected to last for 10 rounds before dropping in the 11th round, assuming he doesn’t use any healing spells or lay on hands. For simplicity the wymrlings didn’t use their breath weapons at all.

You take this absurdly reliable talent for not getting hit by attacks and spread those attacks out across the party and this paladin will rarely have to polish his armor.

Now, I would be remiss if I did not mention that AC is not the only part of combat survivability. An armor class of 30 will do you no good against spells that damage on failed saving throws. But AC is still a huge part of combat survivability.

I get that this is oversimplified in comparison to actual combat. But I think it demonstrates the point well enough. In my party of 5, our Paladin plays the tank role very well. Most of our combat encounters are 3-5 rounds and we have 1 or 2 per 4 hour session. We are also 6th level, his AC is 19 and I still feel that he almost never gets hit. From experience, 19 is very good. An armor class of 23 is broken.

### So what do I do?

This question has some great suggestions for handling this in a way that is engaging and fun for both the DM and the player: I gave a too powerful magic item at too low level for a bad reason, what to do?
This situation is a little bit different than the specific situation detailed there, but the ideas and principles can still apply.