object oriented – Python Back-end registration validation

I am working on a personal project (Flask CRUD app) and I am currently building the user service. I am trying to use as less as libraries as possible (that’s why I do not use WTF-forms for example, just for learning purposes). I am really not sure about a couple of things.

I am aware that form validation should be handled in both front and back-end (or at the very least on the back-end). In order to validate a new user, I am (currently) checking 3 things:

1) email does not already exist on the db (can only be verified on the back-end)

2) password is strong enough (can be done in both front and back end)

3) password and password_confirm matches (can be done in both front and back end)

My goal is to display a small error message on the registration page if either at least one those errors appears. Currently, I am checking option 1, 2 and 3 and the back-end but only return True if the registration is valid otherwise, False.

Since case 1 and 2 can directly be handle also on the front-end, can I display the error message using JavaScript and not from the back-end? I am still confused on what would be the best return for validate_registration (currently a Boolean).

Also, I am not quite sure my code is over-engineered, I made a RegistrationForm class just to validate a registration form. I did that because I am able to pick validations methods from my validators.py which may be used in other Classes as well.

So this is what I did so for for the registration form:

user/blueprints/routes.py

@user.route('/new-user',methods = ('POST'))
def register_user():
    form_email = request.form.get('email')
    form_password = request.form.get('psw')
    form_password_repeat = request.form.get('psw-repeat')
    registration_form = RegistrationForm(form_email, form_password, form_password_repeat).validate_registration()
    
    if registration_form:
        new_user = UserService().register_user(form_email, form_password)
        user_repository = UserRepository(conn, 'users')
        user_repository.add_user(new_user)
        user_repository.save()
        return "ok" #will probably change return statements later on
    return "not ok" #will probably change return statements later on

user/blueprints/forms.py

from prepsmarter.blueprints.user.validators import email_already_in_use, password_matching

class RegistrationForm():
    def __init__(self, email, pwd_1, pwd_2):
        self.email = email
        self.pwd_1 = pwd_1
        self.pwd_2 = pwd_2

    def validate_registration(self):
        is_valid = email_already_in_use(self.email) and is_strong_password(self.pwd_1) and password_matching(self.pwd_1, self.pwd_2)
        return is_valid

class LoginForm():
 # to do

user/blueprints/validators.py

import re 
from email_validator import validate_email, EmailNotValidError
from prepsmarter.extensions import conn

def is_strong_password(password):
    length_error = len(password) < 8
    digit_error = re.search(r"d", password) is None
    uppercase_error = re.search(r"(A-Z)", password) is None
    return length_error and digit_error and uppercase_error
    
def is_email_formated_correctly(email):
    is_correct = True
    try:
        validate_email(email)
    except EmailNotValidError:
        is_correct = False
    return is_correct

def password_matching(pwd_1, pwd_2):
    return pwd_1 == pwd_2

    
def email_already_in_use(email):
    sql = "SELECT CASE WHEN EXISTS ( SELECT * FROM users WHERE email = (%s)) THEN 1 ELSE 0 END;"
    cursor = conn.cursor()
    cursor.execute(sql, (email))
    res = cursor.fetchall()
    return res == 1 

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.

object oriented – How could I construct a C# function that takes in a credit limit and advance amount and outputs an Amount and APR?

0

The Amount and APR will be set as a percentage of the credit limit. The split will be 50%, 25%, and 25% of the credit limit compared to the advance amount. APR starts at 249 and increased 25% each time.

For example :

My credit limit is $1000 and my advance amount is $800. My output should be the following:

{ Amount: 500, APR: 249.00 }, 
{ Amount: 250, APR: 311.25 },
{ Amount: 50, APR: 373.50 }`

or

My credit limit is $1000 and my advance amount is $700. My output should be the following:

{ Amount: 500, APR: 249.00 },
{ Amount: 200, APR: 311.25 }

My code works but I know that it is not best practice and would like to be more efficient. I know there is a more mathematical way to get this done it is just not coming to me. Such as the Environment.Exit(-1) should not be used but I needed it otherwise some outputs were incorrect.

My Code:

public static int CreditLimit { get; set; }
        public static int AdvanceAmount { get; set; }
        public static int Amount { get; set; }
        public static int APR { get; set; }

    public Bam(int creditLimit, int advanceAmount, int amount, int apr)
    {
        CreditLimit = creditLimit;
        AdvanceAmount = advanceAmount;
        Amount = amount;
        APR = apr;
    }

    //FIRST AMOUNT CALCULATION

     public decimal EquationForOutput()
    {
        Amount = ((int)(CreditLimit * .5));
        if (AdvanceAmount <= CreditLimit * .5)
        {
            Amount = AdvanceAmount;
            return Amount;
           
        }
        return Amount;
    }



class Program
    {
        static void Main(string() args)
        {
            int amount = 0;
            int apr = 249;

        Console.WriteLine("Enter Credit Limit");
        int creditLimit = (int)Convert.ToInt64(Console.ReadLine());


        Console.WriteLine("Enter Advance Amount");
        int advanceAmount = (int)Convert.ToInt64(Console.ReadLine());

        Bam nums = new Bam(creditLimit, advanceAmount, amount, apr);
        amount = (int)nums.EquationForOutput();

        Console.WriteLine($"Amount: {amount}");
        Console.WriteLine($"APR: {apr}");



        //SECOND AMOUNT AND APR

        var newApr = (apr * .25) + apr;
        if (advanceAmount <= creditLimit * .5)
        {
            Environment.Exit(-1);
        }
        else if (advanceAmount -amount < creditLimit * .25)
        {

            Console.WriteLine($"Amount: {advanceAmount-amount}");
            Console.WriteLine($"APR: {newApr}");

            Environment.Exit(-1);
        }
        
        else
        {
            Console.WriteLine($"Amount: {amount * .5}");
            Console.WriteLine($"APR: {newApr}");
        }


        //THIRD AMOUNT AND APR
        
        int newAmount = (int)(advanceAmount - (creditLimit * .25) + amount) - creditLimit;
        
        bool endTrue = Convert.ToBoolean(newAmount);

        if (endTrue)
        {
            newApr = (apr * .5) + apr;
            Console.WriteLine($"Amount: {(advanceAmount - amount) - amount * .5}");
            Console.WriteLine($"APR: {newApr}");
        }
    }

object oriented – Just Software Design

Anytime I managed to write a complete piece of software in the past, (none of my systems were huge), I never made any design artifacts such as a UML diagram or pseudocode document, but simply conceived of how parts of it should work and coded it until I had developed the full system. The only form of planning I did was the occasional use of a todo list.

I learned in my computer science courses that this is the wrong approach, and that design artifacts such as pseudocode documents, flow charts, etc, should be made before any code is written. But now I am getting stuck trying to figure out how to design an application.

I don’t know UML, and I can’t simply use hierarchical diagrams or flow charts because the systems I want to create consist of components/objects that interact with one another. Therefore, I need to use diagrams that represent objects/components, their interfaces, and the interactions among them. But without knowing UML I find myself unable to do this. Furthermore, I do not even know how to begin designing an application with such diagrams, as the last time I attempted it I immediately experienced a mental block.

I searched the internet for simple explanations on UML diagrams but I could not find any. Nor could I find any free software for drawing such diagrams. I also find it difficult to find information on how to design software. There are plenty of articles on design patterns, and for the most part I understand them, but there is hardly any information of software design itself.

I even had a job at a small startup where I built things without drawing diagrams and they worked without any problem. But now I find it difficult to code simple programs, either because I am too lazy to rewrite and extend code or because I am actually getting stuck. I need to learn how to design software with diagrams and pseudocode.

I tried to design an rewrite of a simple application I wrote for making and editing outlines and the only thing I wrote on the paper were names of interfaces similar to classes I had already partially implemented in C#: IOutlineDocumentsView, IOutlineDocumentsController, IOutlineDocumentView, IOutlineDocumentController, etc.

I don’t even code bottom-up, I code in a haphazard inside-out outside-in ways manner. I start coding a class and then when I am about to implement a call to a method I didn’t write yet, I stop writing the method I am already working on and start writing the other method. I can’t code top-down because then I would never get around to running my code and there is always a strong possibility that the bulk of my system will not function.

That’s why I like to start out with a small program and make it larger over time. I never really built a very large application, but I did build a web application at my job that grew as features were requested. And even for the first version I had to build it one feature at a time.

So my question is how am I supposed to design software seeing I am on disability for mental illness which probably has decreased my IQ to below average level?

object oriented design – Can someone suggest what pattern I used mistakenly and is it correct in this situation. Any alternative?

Client_1 uses –> IService_1 and thus Service1_impl

public interface IService_1
{
    void DoTask_1();
}

public class Service1_impl : IService_1
{
    private readonly IDepService_1_v1 _depService_4;
    private readonly IDepService_2_v1 _batchdepService_4;
    private readonly IDepService_3_v1 _depService_2;
    private readonly IDepService_4_v1 _depService_3;

    public Service1_impl(
              IDepService_1_v1 depService_4, 
              IDepService_2_v1 batchdepService_4, 
              IDepService_3_v1 depService_2, 
              IDepService_4_v1 depService_3)
    {
        _depService_1 = depService_1;
        _depService_2 = depService_2;
        _depService_3 = depService_3;
        _depService_4 = depService_4;
    }
    
    public void DoTask_1()
    {
      // perform some work with help of all depServices_with_v1.
    }
}

Some new functionality added for Client_2, so I developed like below.

**Client_2 uses –> IService_1_v2 and thus Service_1_v2_impl **

Service_1_v2_impl now depends on IDepService_1_v2, IDepService_2_v2, IDepService_4_v2 which follow same patter. So IDepService_1_v2 has base interface as IDepService_1_v1 and implementation of IDepService_1_v2 has a base class as implementation of IDepService_1_v1 and so on.

public interface IService_1_v2 : IService_1
{
    void DoTask_2();
}

public class Service_1_v2_impl : Service1_impl, IService_1_v2
{
    private readonly IDepService_1_v2 _depService_1;
    private readonly IDepService_2_v2 _batchdepService_2;
    private readonly IDepService_3_v1 _depService_3;
    private readonly IDepService_4_v2 _depService_4;

    public Service1_impl(
              IDepService_1_v2 depService_1, 
              IDepService_2_v2 batchdepService_2, 
              IDepService_3_v1 depService_3, 
              IDepService_4_v2 depService_4)
    {
        _depService_1 = depService_1;
        _depService_2 = depService_2;
        _depService_3 = depService_3;
        _depService_4 = depService_4;
    }
    
    public void DoTask_2()
    {
      // perform some work with help of all_depServices_with_v1.
      base.DoTask_1();
      
      // perform some work with help of all_depServices_with_v1_OR_v2.
    }
}

I got review comment – this may cause interface explosion. so whenever a new requirement/ client going to be added, new set of interfaces. better patter is builder or bridge pattern.

I read through bridge pattern and to me it’s still going to have interfaces explosion.

I didn’t go through any pattern while writing above code, but wondering if above code represent any pattern.

object oriented – Shopping website Design

I am in middle of shopping website design. As of now I am stuck at one point and need a little feedback. Let us say I have an order class defined as follow:

class Order {

    Payment payment;
    Address ShippingAddress
    int orderId;
    List<Item> orderItem;
    double orderValue;  
    Buyer buyer;
    Date orderDate;
    NotificationService notificationService;
    Shipment shipment;
    
    List<OrderLog> orderLog;

    public OrderStatus placeOrder();
    public OrderStatus trackOrder();
    public void addOrderLogs();
    public PaymentInfo makePayment();
    public int createShipment();

}

Does it make sense to have placeOrder(),makePayment() etc.,API in order class? Or shall I make a separate OrderManager that helps to do all order related stuff and order will act as a pojo?

To me first one seems correct because the placeOrder(),makePayment() seems to me as behaviours of order and they should be in order class but on other class I think it is too much for an order class to do.Am i violating some SOLID principle by taking one approach over another?

object oriented – C# code for dhond’t voting method UK Parliament

Please can you check if the code i have written follows 4 rules of encapsulation well enough, if there is anything that could be improved or is just wrong iam happy to change (very new to c# sorry if its awful).

The code implements the “Dhond’t Method” which is a polling system. https://www.bbc.co.uk/news/uk-politics-27187434

MAIN

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

namespace Voting_System
{
    class Program
    {  
        static void Main(string() args)
        {
            // Establish the file path 
            string filepath = @"C:UsersmatheOneDriveDocumentsAll AssignmentsVoting Systeminputdata.txt";

            // Store values in a list of string
            List<string> file = File.ReadAllLines(filepath).ToList();

            // Puts each party into a list of Party and display Name + Votes
            List<Party> partys = new List<Party>();
            foreach (string line in file)
            {
                string() items = line.Split(',');
                Party p = new Party(items(0), Convert.ToInt32(items(1)));
                partys.Add(p);
            }

            // Ask user for thresh hold and also calculate total votes
            Console.WriteLine("What is the threshold for partys (%) ?");
            double threshold = Convert.ToDouble(Console.ReadLine());

            // Ask user how many seats they want to allocate
            Console.WriteLine("nHow many seats do you want to allocate in total? e.g. 8");
            int seatsCount = Convert.ToInt32(Console.ReadLine());

            // Find total votes
            int totalVotes = 0;
            foreach (Party p in partys)
            {
                totalVotes += p.Votes;
            }
            Console.WriteLine($"nTOTAL No OF COMBINED VOTES FOR ALL PARTIES 2020 : {totalVotes}n");

            // Displays percent of votes for each party 
            Console.WriteLine($"PARTIES THAT MEET THE {threshold}% INPUTTED THRESHOLD:");
            foreach (Party p in partys)
            {
                if (p.PercentOfVotes(totalVotes) > threshold)
                {
                    Console.WriteLine($"{p.Name} has {p.PercentOfVotes(totalVotes)} % of total votes.");
                }
            }

            // Find intial party with highest votes
            Party biggestVote = partys.Aggregate((v1, v2) => v1.Votes > v2.Votes ? v1 : v2);
            biggestVote.Seats += 1;
            biggestVote.DivideParty();

            // Keep looping through partys and applying dhond't method until all seats are taken
            int totalSeatsCount = 0;
            while (totalSeatsCount != seatsCount)
            {
                Party biggestVotes = partys.Aggregate((v1, v2) => v1.NewVotes > v2.NewVotes ? v1 : v2);
                biggestVotes.Seats += 1;
                biggestVotes.DivideParty();

                foreach (Party p in partys)
                {
                    totalSeatsCount += p.Seats;
                }

                if (totalSeatsCount != seatsCount)
                {
                    totalSeatsCount = 0;
                }
            }

            Console.WriteLine("nWE HAVE 5 SEATS ALLOCATED:");
            // Print out all partys and there properties to user
            foreach (Party p in partys)
            {
                Console.WriteLine(p);
            }

            // Keeps console open
            Console.ReadLine();
        }
        
    }
}

PARTY CLASS

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

namespace Voting_System
{
    class Party
    {
        // properties for each party
        public string Name { get; private set; }
        public int Votes { get; private set; }
        public int NewVotes { get; set; }
        public int Seats { get; set; }

        // Constructor for party class 
        public Party(string name, int votes)
        {
            Name = name;
            Votes = votes;
            NewVotes = votes;
        }

        // Returns percentage of votes for your party
        public double PercentOfVotes(double totalVotes) => (Votes / totalVotes) * 100;

        // When ever you print the object of this class return this
        public override string ToString()
        {
            return $"Name: {Name} Votes: {Votes} Seats: {Seats}";
        }

        // Applies Dhond't method of division 
        public void DivideParty()
        {
            NewVotes = Votes / (1 + Seats);
        }
    }
}

DATA INPUT FILE

Brexit Party,452321,BP1,BP2,BP3,BP4,BP5;
Liberal Democrats,203989,LD1,LD2,LD3,LD4,LD5;
Labour,164682,LAB1,LAB2,LAB3,LAB4,LAB5;
Conservative,126138,CON1,CON2,CON3,CON4,CON5;
Green,124630,GR1,GR2,GR3,GR4,GR5;
UKIP,58198,UKP1,UKP2,UKP3,UKP4,UKP5;
Change UK,41117,CUK1,CUK2,CUK3,CUK4,CUK5;
Independent Network,7641,INET1,INET2,INET3,INET4,INET5;
Independent,4511,IND1;

object oriented design – Is it wrong to extend an inner static class in java? (Builder pattern)

I’m working on a java project for the university. The project is a card game in which you travel around a 2D map and fight against some enemies. My part consists of creating the deck and the cards.

I made the card interface, an abstract card and an implementation that extends the abstract card and implements the interface.

Now I also want an internal static constructor in the abstract class and a related constructor implementation in all classes that extend the abstract class. I have extended the constructor in the implementation, but I don’t know if it is correct to extend a static class.

The idea came to me from:

Effective Java, 3rd edition, Joshua Bloch, Item 2: Consider a builder when faced with many constructor parametersconstructor parameters

The question is: Is it correct to extends a static inner class?

Because what I would mainly like is to “force” all classes that extend the abstract class to have a builder, since the constructor has many parameters.

object oriented – Snake Game design

I am designing Classic Snake game using OOPS.I will have the following classes at top level :

Game
{
Board board,
Snake snake;
}

Board
{
Cell cells[];
}

Cell
{
int x,
int y,
Type type;
}

Type
{
SNAKE,
FOOD,
EMPTY
}

Snake
{
List<Cells> snakeParts;
}

I am a little confused on following point:

Can snake be part of Board class as follow?

Board
{
Cell cells[];
Snake snake;
}

Like instead of Game class having Snake object, is it better for Board class to have snake object?Because it makes sense to say that BOARD ‘has-a’ snake instead of Game ‘has-a’ snake .

java – Object Oriented development

I recently got into a conversation with a co-worker who identified object oriented programming as over engineering in favor of Anemic domain model (simply bunch of classes used as a place holder for procedures). So my question is, since when did object oriented programming became over engineering? Specially when you are using languages that were created on the object oriented paradigm such as java or C++. I don’t really mean to complain or anything but want to get some idea on how many people really do think that OO is over engineering.