design patterns – Should there only ever be one instance of a ViewModel object?

Assume a rather simplistic model:

class Person{   
   static List<Person> LivingPersons

   String Name
   List<Person> Dependents 
}

From this it can (hopefully) be seen that a single Person object can be both within the LivingPersons list and within the Dependents list of another Person object. Similarly, if there were a couple of ViewModels to represent this model:

class ViewModel_LivingPersons{
   static List<ViewModel_Person> LivingPersons
}

class ViewModel_Person{
   String Name
   List<ViewModel_Person> Dependents   
}

If I had a single Person object that resided in both the LivingPersons list and within the Dependents list of another Person, my gut feeling tells me that as it is the same model object being represented there should only ever be one instance of a ViewModel_Person to represent this model object. However, I do not know why, nor if this is best practice.

I’m not certain of the best practices here. I’ve done a bit of searching, but cannot find anything on this particular issue.

c# – Object orianted programing in a game

Right now i have a snake game that is working but i need a way to make my code look better and work better.

A method i named “GameSense” is very long and i need a way to make it more object oriented. I want to use Enums.

This is what my teacher sent back to me:

The game is very nice and nicely working tail! The test you have also follows the right idea but uses an UpdatePosition method that you have not implemented. I’m also thinking about your class pixel – you do not use it for anything in the rest of the game. You should use it instead of e.g. berryx, berryy. What I am trying to access is more use of object orientation and division into methods, and not a single long method like GameSense right now. Also want to see you use enum / bool instead of strings for e.g. the variables movement and buttonpressed. However, I’m glad you got an interface on a corner!

As you can see… i feel pretty suck right now.
What do i need to do here inorder to make the program be more object orianted?
Any tips along the way would be super helpful!
Thanks!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Snake
{
    /// <summary>
    /// Start class, everything goes from here.
    /// Made by Karwan!
    /// </summary>
   public class Starter : InterF
    { 
        public static object Key { get; private set; }

        /// <summary>
        /// Main method.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string() args)
        {
            //Making the text green and also given a player 
            //options to chose from. 
            Console.ForegroundColor = ConsoleColor.Green;
            bool loopC = true;
            while (loopC)
            {
                string mystring = null; Console.WriteLine("Welcome to Snake.nPress S+Enter to start or press Q+Enter to exit.");
                mystring = Console.ReadLine();
                switch (mystring)
                {
                    case "Q":
                        Environment.Exit(0);
                        break;
                    case "S":
                        Console.WriteLine("Starting game!");
                        System.Threading.Thread.Sleep(4000);
                        loopC = false;
                        break;
                    default:
                        Console.WriteLine("Invalid Entry.. Try again.");
                        break;
                }

            }

            //Call for GameSense if
            //they want to play.
            GameSense(); 

        }


      
        /// <summary>
        /// Game object!
        /// </summary>
        public static void GameSense()

        {
            //Game console height/width.
            Console.WindowHeight = 30;
            Console.WindowWidth = 70;
            int screenwidth = Console.WindowWidth;
            int screenheight = Console.WindowHeight;
            Random randomnummer = new Random();
            //Lenght of tail == current score.
            int score = 2;
            int gameover = 0;
            //Gather positions from pixel class.
            pixel positions = new pixel();
            positions.xpos = screenwidth / 2;
            positions.ypos = screenheight / 2;
            positions.Black = ConsoleColor.Red;
            string movement = "RIGHT";
            //Position manegment.
            List<int> xpos = new List<int>();
            List<int> ypos = new List<int>();
            int berryx = randomnummer.Next(0, screenwidth);
            int berryy = randomnummer.Next(0, screenheight);
            //Time manegment.
            DateTime time1 = DateTime.Now;
            DateTime time2 = DateTime.Now;
            string buttonpressed = "no";

            
            //Draw world from GameWorld.cs.
            GameWorld.DrawBorder(screenwidth, screenheight);

            while (true)
            {
                GameWorld.ClearConsole(screenwidth, screenheight);
                if (positions.xpos == screenwidth - 1 || positions.xpos == 0 || positions.ypos == screenheight - 1 || positions.ypos == 0)
                {
                    gameover = 1;
                }

                Console.ForegroundColor = ConsoleColor.Green;
                if (berryx == positions.xpos && berryy == positions.ypos)
                {
                    score++;
                    berryx = randomnummer.Next(1, screenwidth - 2);
                    berryy = randomnummer.Next(1, screenheight - 2);
                }
                for (int i = 0; i < xpos.Count(); i++)
                {
                    Console.SetCursorPosition(xpos(i), ypos(i));
                    Console.Write("*");
                    if (xpos(i) == positions.xpos && ypos(i) == positions.ypos)
                    {
                        gameover = 1;
                    }
                }
                if (gameover == 1)
                {
                    break;
                }
                Console.SetCursorPosition(positions.xpos, positions.ypos);
                Console.ForegroundColor = positions.Black;
                Console.Write("*");
                //Food color & position.
                Console.SetCursorPosition(berryx, berryy);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("*");
                Console.CursorVisible = false;
                time1 = DateTime.Now;
                buttonpressed = "no";
                while (true)
                {
                    time2 = DateTime.Now;
                    if (time2.Subtract(time1).TotalMilliseconds > 500) { break; }
                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo info = Console.ReadKey(true);
                        //Connecting the buttons to the x/y movments. 
                        if (info.Key.Equals(ConsoleKey.UpArrow) && movement != "DOWN" && buttonpressed == "no")
                        {
                            movement = "UP";
                            buttonpressed = "yes";
                        }
                        if (info.Key.Equals(ConsoleKey.DownArrow) && movement != "UP" && buttonpressed == "no")
                        {
                            movement = "DOWN";
                            buttonpressed = "yes";
                        }
                        if (info.Key.Equals(ConsoleKey.LeftArrow) && movement != "RIGHT" && buttonpressed == "no")
                        {
                            movement = "LEFT";
                            buttonpressed = "yes";
                        }
                        if (info.Key.Equals(ConsoleKey.RightArrow) && movement != "LEFT" && buttonpressed == "no")
                        {
                            movement = "RIGHT";
                            buttonpressed = "yes";
                        }
                    }
                }
                //Giving the connections value
                //to change x/y to make the movment happen.
                xpos.Add(positions.xpos);
                ypos.Add(positions.ypos);
                switch (movement)
                {
                    case "UP":
                        positions.ypos--;
                        break;
                    case "DOWN":
                        positions.ypos++;
                        break;
                    case "LEFT":
                        positions.xpos--;
                        break;
                    case "RIGHT":
                        positions.xpos++;
                        break;
                }
                if (xpos.Count() > score)
                {
                    xpos.RemoveAt(0);
                    ypos.RemoveAt(0);
                }
            }
            Console.SetCursorPosition(screenwidth / 5, screenheight / 2);
            Console.WriteLine("Game over, Score: " + score);
            Console.SetCursorPosition(screenwidth / 5, screenheight / 2 + 1);
            System.Threading.Thread.Sleep(1000);
            restart();
            
        }

        /// <summary>
        /// Restarter.
        /// </summary>
        public static void restart()
        {
        
            string Over = null; Console.WriteLine("nWould you like to start over? Y/N");
            bool O = true;

            while (O)
            {
                Over = Console.ReadLine();
                switch (Over)
                {
                    case "Y":
                        Console.WriteLine("nRestarting!");
                        System.Threading.Thread.Sleep(2000);
                        break;
                    case "N":
                        Console.WriteLine("nThank you for playing!");
                        Environment.Exit(0);
                        break;
                    default:
                        Console.WriteLine("Invalid Entry.. Try again.");
                        break;
                }
            }

        }
        /// <summary>
        /// Set/get pixel position.
        /// </summary>
       public class pixel
        {
            public int xpos { get; set; }
            public int ypos { get; set; }
            public ConsoleColor Black { get; set; }
        }
    }
}

My test class

using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Snake;
using System;
using System.Collections.Generic;
using System.Text;
using static Snake.Starter;

namespace Snake.Tests
{
    (TestClass())
    public class StarterTests
    {
        /// <summary>
        /// Testing the movment.
        /// </summary>
        (TestMethod())
        public void test()
        {
           
           var pos = new pixel();
            pos.xpos = 10;
            pos.ypos = 10;

            // this is the operation:
            UpdatePosition(pos, "UP");

            // check the results
            NUnit.Framework.Assert.That(pos.xpos, Is.EqualTo(10));
            NUnit.Framework.Assert.That(pos.ypos, Is.EqualTo(9));
        }

        /// <summary>
        /// Updating pixel class.
        /// </summary>
        /// <param name="pos"></param>
        /// <param name="v"></param>
        private void UpdatePosition(pixel pos, string v)
        {
            throw new NotImplementedException();
        }
    }
}

This is just the gameworld:

using System;
using System.Linq;

public class GameWorld 
{


    /// <summary>
    /// Clear console for snake.
    /// </summary>
    /// <param name="screenwidth"></param>
    /// <param name="screenheight"></param>
    public static void ClearConsole(int screenwidth, int screenheight)
    {
        var blackLine = string.Join("", new byte(screenwidth - 2).Select(b => " ").ToArray());
        Console.ForegroundColor = ConsoleColor.Black;
        for (int i = 1; i < screenheight - 1; i++)
        {
            Console.SetCursorPosition(1, i);
            Console.Write(blackLine);
        }
    }

    /// <summary>
    /// Draw boared.
    /// </summary>
    /// <param name="screenwidth"></param>
    /// <param name="screenheight"></param>
    public static void DrawBorder(int screenwidth, int screenheight)
    {
        var horizontalBar = string.Join("", new byte(screenwidth).Select(b => "■").ToArray());

        Console.SetCursorPosition(0, 0);
        Console.Write(horizontalBar);
        Console.SetCursorPosition(0, screenheight - 1);
        Console.Write(horizontalBar);

        for (int i = 0; i < screenheight; i++)
        {
            Console.SetCursorPosition(0, i);
            Console.Write("■");
            Console.SetCursorPosition(screenwidth - 1, i);
            Console.Write("■");
        }
    }

}

software – How to return an new Object as Value ?[Sequence Diagram]

within the sequence diagram it is possible to return a value, with return of a method edge, however this is usually done with a simple numeric or string value. Is it possible to return a whole object? For example, I have the task to create a coffee and put 3 sugars in it.

Classes: initiator-Customer, Coffee and Sugar.

Two scenarios for completion:

First

  1. Customer calls new Coffee() which, generates a new coffee object
  2. From coffe object, call the add sugar from Sugar class, three times(loop) with addSugar(this).
  3. Return coffee object with 3 sugars to the Customer

Second

  1. Customer calls new Coffee() which, generates a new coffee object
  2. Return coffee object to customer class.
  3. Call three times(loop) from customer the Sugar class with coffee object as parmeter.

Which one is better ?

Unity Mirror client scene.local player.connection to client.client owned object not working in client

U hmm I’m new to mirror networking I just wanna find objects that the local player has authority, but it doesn’t work on client, is there a solution to this? Well I could make an object tracking script but that will complicate things.
This question might look like I haven’t research anything, truth is I’ve searched everywhere there is just no documentation for this

object oriented – Python (Flask) – User registration system

Opinions always differ on matters like this, but your UserService class seems
like a severe case of over-engineering.

First, three of the methods seem to offer nothing very substantive:
desactivate_user() and reactive_user() just set boolean attributes on a
User instance; and is_active() just returns an attribute. I would encourage
you to simplify things: just operate on the user instance directly.

Second, the update_activity_tracking() does more stuff to the user instance,
but there’s no obvious reason not to move the method into the User class as well.

Third, the update_password() is a good example of a situation where you could
use a property, because you need to perform some calculations before storing
the attribute. Here’s the basic pattern:

class User:

    def __init__(self, password):
        # Initialize an under-the-hood attribute.
        self._password = None

        # Call the setter.
        self.password = password

    @property
    def password(self):
        # The getter just returns it.
        return self._password

    @property.setter
    def password(self, new_password):
        # The setter does the needed calculation.
        self._password = get_hashed_password(new_password)

Fourth, the register_user() method is a natural fit for a classmethod in
the User class:

class User:

    @classmethod
    def register_user(cls, email, password):
        # Python allows you to call functions in keyword style even if the
        # function defines arguments as required positionals. You can use
        # this feature to simplify the code (eliminate some temporary
        # variables in this case) while still preserving code readability.
        today = datetime.today().strftime('%Y-%m-%d')
        return cls(
            email,
            password,
            registration_date = today,
            active = 1,
            sign_in_count = 2,
            current_sign_in_on = today,
            last_sign_in_on = today,
        )

The User.__init__() method has a large number of required parameters. Perhaps
your use case demands that, but you might give some thought to which of the
attributes are truly required in all usages. For example, the method
could default to using registration_date if the two sign-on dates
are not provided (as we do above in register_user()).
Regardless of that decision, if
testing and debugging make direct interaction with __init__() tedious, you
can add more conveniences to the class, again using the @classmethod
mechanism.

Managing user passwords is tricky business, at least in the real world. It’s
good that you store a hashed password rather than the plaintext, but I would
not include even the hashed password attribute in any kind of printing,
logging, etc. Adjust your User.__str__() method accordingly.

In UserRepository.add_user() you can simplify things. If you are testing for
truth, just do it directly (if user.active) rather than indirectly (if user.active == True). Also, bool values in Python are a subclass of int
(for example, 199 + True == 200), so you can delete the conditional logic entirely and
just do something like this:

def add_user(self, user):
    # Long lines can be made more readable by formatting
    # them in the style of pretty-printed JSON. Notice how
    # easy this style is to read, scan visually, and edit flexibly.
    sql = '''
        INSERT INTO users (
            email,
            password,
            is_active,
            sign_in_count,
            current_sign_in_on,
            last_sign_in_on
        )
        VALUES (%s, %s, %s, %s, %s, %s)
    '''.strip()
    cursor = self.conn.cursor()
    cursor.execute(
        sql,
        (
            user.email,
            user.password,
            int(user.active),
            user.sign_in_count,
            user.current_sign_in_on,
            user.last_sign_in_on,
        )
    )
    return cursor.fetchall()

Your capitalization of the User variable within various methods is
inconsistent both with your own usages and with the norms in the wider
Python community: FooBar for class names and foo_bar for instance
variables is the most common approach.

DB operations can fail. If this is just an early learning exercise, you
can safely ignore the problem, but if your goal is to make the application
more robust, the operations should be wrapped in try-except structures,
as hinted at in your code comments.

In my experience, web applications like this will have various classes
representing the entities of interest (User, Book, Author, whatever). And
several of those classes will need DB operations: create, read, update, delete,
etc. And those DB operations will be fairly general, in the sense that if you
write a good method to update one kind of instance (eg, User), it can often be
made to do the same thing for other kinds of instances, provided that the
substantive classes (User, Book, etc) have attributes, properties, or methods
to deliver the information (things like table name and a list of (COL_NAME, ATTRIBUTE_VALUE) tuples) that a general-purpose DB method needs in order to
perform its operation. All of which is to say that UserRepository might
be too narrow of a focus. Instead, think about whether and how you might
convert that class into just Repository.

If this web application is intended to be a long-running application, you’ll
want to wire it up to use the logging framework at some point (rather than
just printing stuff), but that can come whenever you are ready to learn about
it.

Regarding your question about frequency of saving DB changes, don’t worry about
it or overthink it. Build your application with reasonable Python code — you
are off to a good start — and if your application ever needs to achieve higher
scale, solve the problem when it is clearly visible on the horizon. It’s often
easier to change DBs, scale outward (more running instances of your application
in different processes or on different servers), or alter the data schema than
it is to write tricky “save every N operations” code.

python 3.x – Erro ao linkar duas tabelas no SQLAlchemy (sqlalchemy.exc.InvalidRequestError: Object ‘is already attached to session ‘5’ (this is ‘6’)

Para entender como uma aplicação web é feita em python estou tentando criar uma pagina em que o usuário possa se cadastrar, logar, adicionar comentários sobre suas nebulosas preferidas e então salva-las em seu perfil.
Entretanto na tentativa de adicionar informações em uma tabela (nome da tabela: ‘Nebula_docs’) no SQLAlchemy, parecer haver um conflito com uma outra tabela já criada (nome da tabela: ‘User’)

Obs: por dificuldades no processo minhas tabelas estão no mesmo arquivo .py que a função de run da app. O que definitivamente não é ideal.

Ao rodar o app recebo a seguinte mensagem:

sqlalchemy.exc.InvalidRequestError: Object ‘<Nebula_docs at 0x1a198d84fd0>’ is already attached to session ‘5’ (this is ‘6’)

Aqui esta meu arquivo init.py

import os                                             
from flask import Flask                               
from sqlalchemy import Column, String, Integer        
from sqlalchemy import Float, DateTime, Text, ForeignKey          
from sqlalchemy.orm import relationship              
from flask_sqlalchemy import SQLAlchemy                                  
from flask_login import LoginManager                 
from datetime import datetime


db = SQLAlchemy()                                     

# primeira tabela com os dados do usuário
class User(db.Model):                     
    __tablename__='User'

    id = Column(Integer, primary_key=True)            
    email = Column(String(100), unique=True)          
    password = Column(String(100))                    
    name = Column(String(100))                        
    catalog = relationship('Nebula_docs', backref='author', lazy=True) 
    
    #funçãos que geralmente compõe o UserMixin

    @property                            
    def is_active(self):                  

    def get_id(self):                    
        return True

    def is_authenticated(self):          
        return True

    def is_anonymous(self):              
        return False

#segunda tabela em que os dados da Nebulosa que o usuário completar
class Nebula_docs(db.Model):
    __tablename__='Nebula_docs'

    id = Column(Integer, primary_key=True)
    day_register = Column(DateTime,nullable=False, default=datetime.utcnow)
    nebula_name = Column(String(50), nullable=False)
    ngc_code = Column(String(6))
    comment = Column(Text)
    user_id = Column(Integer, ForeignKey('User.id'), nullable=False)

#função de inicialização da app
def create_app():                                                   
    app = Flask(__name__)                                            
    
    #configurando a pp
    app.config.update(SECRET_KEY=os.urandom(24))                     
    app.config('SQLALQUEMY_DATABASE_URI') = 'sqlite:///db.sqlite3'   
    
    #iniciando o banco de dados
    db.init_app(app)                                                 
    with app.app_context():                                          
        db.create_all()                                              
    
    #iniciando o login do usuario
    login_manager = LoginManager()                                   
    login_manager.login_view= 'auth.login'                           
    login_manager.init_app(app)                                     

    @login_manager.user_loader                                       
    def load_user(user_id):                                          
        return User.query.get(int(user_id))                         


    from .main import main as main_blueprint                         
    app.register_blueprint(main_blueprint)                           
    from .auth import auth as auth_blueprint                         
    app.register_blueprint(auth_blueprint)                           

    return app      

O arquivo que contém o registro dos dados na tabela ‘Nebulas_docs’ é o seguinte:
main.py

from flask import Blueprint, render_template, url_for, request, redirect, flash
from flask_login import login_required, current_user
from .__init__ import User
from .__init__ import Nebula_docs
from .__init__ import db

main = Blueprint('main', __name__)     __name__ is the name o the project

@main.route('/')
def index():                           
    return render_template('index.html')

@main.route('/profile')                 
@login_required
def profile():
    return render_template('profile.html', name= current_user.name)

@main.route('/new')
@login_required
def new_nebula():
    return render_template('add_nebula.html')

#aqui se adiciona os dados da nebulosa

@main.route('/new', methods= ('POST'))
@login_required
def new_nebula_post():
    nebula_name = request.form.get('nebula_name')
    ngc_code = request.form.get('ngc_code')
    comment = request.form.get('comment')

    nebula = Nebula_docs(nebula_name=nebula_name, ngc_code=ngc_code, comment=comment, author=current_user)
    db.session.add(nebula)     #creio que aquie steja o erro
    db.session.commit()

    flash('Your nebula has been added')

    return redirect(url_for('main.index'))

#aqui se guardaria as informações definidas na função anterior

@main.route('/user_nebulas')
@login_required
def all_user_nebulas():
    user = User.query.filter_by(email=current_user.email).first_or_404()
    catalog = user.catalog
    return render_template(url_for('all_nebulas.html'), catalog=catalog, user=user)

creio que esteja havendo uma sobreposição das tabelas User e Nebula_docs, que estão compartilhando o mesmo db, mas não sei como resolver isso de maneira alguma.

Se alguem puder me ajudar ficaria imensamente grato.

object oriented – A Tiny Image Tagger Implementation in C#

I am trying to implement a tiny image tagger with customized tag options in C#. The main window is as follows.

MainUIFigure

The left block is a picture box MainPictureBox and there are two buttons, PreviousButton and NextButton. Furthermore, there are some tags in a group box AttributeGroupBox. A save button SaveButton is used for saving tagged information.

The implemented functions:

  • Load images automatically in the folder which the program located.

  • Each image could be tagged.

  • The tag information of each image could be saved as a text file LabelResult.txt.

The experimental implementation

class Attribute
{
    public enum AttributeEnum
    {
        Mountain,
        Cat
    }

    public AttributeEnum attributeEnum;

    public override string ToString()
    {
        if (this.attributeEnum.Equals(AttributeEnum.Cat))
        {
            return "Cat";
        }
        if (this.attributeEnum.Equals(AttributeEnum.Mountain))
        {
            return "Mountain";
        }
        return "";
    }
}
public partial class Form1 : Form
{
    List<string> ImagePaths;
    List<Attribute> AttributeList;
    int index = 0;
    string targetDirectory = "./";
    public Form1()
    {
        InitializeComponent();

        
        System.IO.FileSystemWatcher watcher = new FileSystemWatcher()
        {
            Path = targetDirectory,
            Filter = "*.jpg | *.jpeg| *.bmp | *.png"
        };
        // Add event handlers for all events you want to handle
        watcher.Created += new FileSystemEventHandler(OnChanged);
        // Activate the watcher
        watcher.EnableRaisingEvents = true;

        ImagePaths = new List<string>();
        
        string() fileEntries = System.IO.Directory.GetFiles(targetDirectory);
        foreach (string fileName in fileEntries)
        {
            string filenameExt = System.IO.Path.GetExtension(fileName);
            if (filenameExt.Equals(".jpg") ||
                filenameExt.Equals(".jpeg") ||
                filenameExt.Equals(".bmp") ||
                filenameExt.Equals(".png")
                )
            {
                ImagePaths.Add(fileName);
            }
        }
        MainPictureBox.SizeMode = PictureBoxSizeMode.Zoom;
        MainPictureBox.Image = Image.FromFile(ImagePaths(0));

        AttributeList = new List<Attribute>();
        
    }

    private void OnChanged(object source, FileSystemEventArgs e)
    {
        ImagePaths.Clear();
        string() fileEntries = System.IO.Directory.GetFiles(targetDirectory);
        foreach (string fileName in fileEntries)
        {
            string filenameExt = System.IO.Path.GetExtension(fileName);
            if (filenameExt.Equals(".jpg") ||
                filenameExt.Equals(".jpeg") ||
                filenameExt.Equals(".bmp") ||
                filenameExt.Equals(".png")
                )
            {
                ImagePaths.Add(fileName);
            }
        }
    }

    private void PreviousButton_Click(object sender, EventArgs e)
    {
        index--;
        if (index <= 0)
        {
            index = 0;
        }
        MainPictureBox.Image = Image.FromFile(ImagePaths(index));
        GC.Collect();
    }

    private void NextButton_Click(object sender, EventArgs e)
    {
        NextAction();
    }

    private void NextAction()
    {
        index++;
        if (index >= ImagePaths.Count)
        {
            index = ImagePaths.Count - 1;
        }
        MainPictureBox.Image = Image.FromFile(ImagePaths(index));
        GC.Collect();
    }

    private void SaveButton_Click(object sender, EventArgs e)
    {
        Attribute attribute = new Attribute();
        
        if (radioButton1.Checked)
        {
            attribute.attributeEnum = Attribute.AttributeEnum.Mountain;
        }
        if (radioButton2.Checked)
        {
            attribute.attributeEnum = Attribute.AttributeEnum.Cat;
        }
        MessageBox.Show(attribute.ToString());
        AttributeList.Add(attribute);
        AttributeListToTxt();
        NextAction();
    }

    private void AttributeListToTxt()
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < this.AttributeList.Count; i++)
        {
            sb.Append(this.ImagePaths(i) + "t" + this.AttributeList(i).ToString() + Environment.NewLine);
        }
        File.WriteAllText("LabelResult.txt", sb.ToString());
    }
}

All suggestions are welcome.

If there is any possible improvement about:

  • Potential drawback or unnecessary overhead
  • The design of implemented methods

please let me know.

c – Naming convention for functions that mutate arguments vs creating a new object

Take the following signature

BigInt* addBigInt(BigInt* arg1, BigInt* arg2);

Traditionally, the safest way to implement this function would be for it not mutate the arguments, and would necessarily need to create a new object to result for the operation. Alternatively, if the aim is to conserve on system memory, arg1 could be the object that the resulting operation would return having mutated that object.

The question is, is there an established naming convention the would delineate the nuance between the two implementation choices? Or is this something that would need to be clearly laid out in the documentation where the developer is establishing the convention?

Let’s assume this is in C where function overloading is not possible.

2d – Design an object for a unity game?

I’m new to game development, I recently started a new game project. I use the unity engine for game development. Now, what is the best program for object (vehicles, plant, etc) designing? It should be easy to learn and not too complicated. I read about Blender but in my opinion, it’s too complicated.

PS: I only have 2 weeks to learn design. It’s a school project.

object oriented design – How to create uniform interface of C++ classes without virtual methods?

I have been developing control software in C++. My hardware consists of a microcontroller with an integrated a/d converter and an external on board a/d converter. Both of these a/d converters have different features but there are some commonalities (both of them are capable to offer value of
given analog input).

// analog inputs
enum class Input
{
  Channel_00,
  Channel_01,
  Channel_02,
  Channel_04,
  Channel_05,
  Channel_06,
  Channel_07
};

// driver of the internal a/d converter
class AdcInt
{
  public:
    float getValue(Input input);
};

// driver of the external a/d converter
class AdcExt
{
  public:
    float getValue(Input input);
};

Based on the drivers for the a/d converters I am going to start building the application layer. One of the building stones of my design is the AnalogInput class. This class is intended to exploit the drivers and offers some additional services e.g. conversion the raw value into the physical units.

class AnalogInput
{
  public:
    float getConvertedValue();
}

I have been thinking about how to ensure that the AnalogInput class can operate with both the driver objects (AdcInt, AdcExt) which is necessary because the analog inputs can be connected to any of the a/d converters and I need to work with all the analog inputs in uniform manner.

My first idea how to do that is based on common interface for all the a/d converter drivers let’s say AdcDriver and defining the virtual getValue method as a part of this interface. The AnalogInput class would then receive pointer to the AdcDriver interface in its constructor. The drawback of this idea is that the getValue method is virtual which is unsuitable for usage in the interrupt service routine (which is my requirement).

Due to the drawback of my first idea I have started to look for another approach how to create common interface AdcDriver without virtual method. I have found the so called curiously recurring template pattern (CRTP).

template<class T>
class AdcDriver 
{
  public:
    float getValue(Input input)
    {
      return static_cast<T*>(this)->getValue(input);
    }
}

class AdcInt : public AdcDriver<AdcInt>
{
  public:
    float getValue(Input input)
    {
      // ... implementation specific for AdcInt
    }
}

class AdcExt : public AdcDriver<AdcExt>
{
  public:
    float getValue(Input input)
    {
      // ... implementation specific for AdcExt
    }
}

template<class T>
class AnalogInput
{
  public:
    AnalogInput(T& _driver, Input _input_id) : driver(_driver)
    {
      input_id = _input_id;
    }

    float getConvertedValue()
    {
      return convert(driver.getValue());
    }

  private:
    T& driver;
    Input input_id;

    float convert(float); 
}

int main(int argc, char** argv) {

  AdcInt internal_adc;
  AdcExt external_adc;

  AnalogInput<AdcInt> analog_input_01(internal_adc, Input::Channel_01);
  AnalogInput<AdcExt> analog_input_02(external_adc, Input::Channel_02);

  analog_input_01.getConvertedValue();
  analog_input_02.getConvertedValue();

  return 0;
}

Do you think that the second approach which I have described above is appropriate solution of my problem? If you don’t think so can you recommend me better idea?