Oop Any sensible examples of creating inheritance without creating subtyping relations?

I've been teaching OOP and was trying to convey to my students the important difference between inheritance and the creation of a subtype relation between two types. For example, in C++, I could use private inheritance to ensure that nobody outside sees the subtyping relation. However, while I can think of a lot of situations where I wouldn't want to create a subtyping relation (e.g., implementing a Stack via a doubly-linked list class), I can't really think of good design examples where I woul

Oop Is type checking ever OK?

Is type checking considered bad practice even if you are checking against an interface? I understand that you should always program to an interface and not an implementation - is this what it means? For example, in PHP, is the following OK? if($class instanceof AnInterface) { // Do some code } Or is there a better way of altering the behaviour of code based on a class type? Edit: Just to be clear I am talking about checking whether a class implements an interface not just that it is an i

Oop Learning object oriented thinking

I'm currently working on a small 2D game-engine in C++, but I am now facing a daemon - I suck at designing a 'system of classes' that actually works. There are a blockade in my mind that disables me from seeing where I should use a class and where I should not. I was reading an article about engine-design and it purposed to use a 'State' class to manage the state of different game entries (I was using an int). It also suggested that all objects for the game (not io/video/sound etc) derive from

Getting lost in the OOP joungle when trying to put a method in the right place etc

It's not as though I don't understand OOP concept, and what should be done when, but sometimes I just mentally get lost in that. What better from an example? So I needed to download a file to a temp path, I decided to get the temp path not by the normal methods of dot net, because of irrelevant reason. So I wrote my own method for this string GetTempFileSafe(string extension, out FileStream), nice, isn't it? But hey, wait a minute, this is not the right place for this method... This method migh

Oop Problem Extending A Class in Clojure: ClassFormatError: Duplicate field name&signature

I'm trying to extend JButton with Clojure, but I ran into a problem when I try to create my own constructors. Whenever I use :constructors with :gen-class I keep getting a "ClassFormatError: Duplicate field name&signature" message when I try to instantiate my class. I think I'm following the Clojure docs properly. Am I doing something wrong? Example: (ns test.gui.button (:gen-class :extends javax.swing.JButton :constructors {[] [String]} :init init)) (defn -init [] [["Click

Oop Where does the idea that an object should only do one thing come from?

I'm not sure I agree with it, so I'd like to find the book or journal article behind this idea so that I can check that I understand exactly what they're saying and what context they mean it. I think I understand the idea - I just want to know the source so I can check where the idea comes from. why I'm asking: The term "do one thing" is vague and could mean lots of things including "only have one method per class" (ridiculous)... I think it could mean a single responsibility (i.e. lots of me

Basic question about OOP

I often have the same trouble when I have to design my class for a web application. The requirements are : - maintainable (no copy-paste for instance) - layers fully separated (the business layer doesn't have to know which method of the data layer is used) - high performance : don't load useless data. First I have a table with all my customers and their addresses : Code : Customer --Id --Name --Address ----City ----ZC ----Street Now I want a table (in another page) with all my customers and

Oop How to apply Single Responsibility Principle to a service class

Suppose we are designing a UserServiceImpl class which does CRUD (Create, Read, Update, and Delete) operations. In my view Create, Read, Update, and Delete are four reasons for a class to change. Does this class violates Single Responsibility Principle? If it violates, then should we have four classes like CreateUserServiceImpl, ReadUserServiceImpl, UpdateUserServiceImpl, and DeleteUserServiceImpl. Isn't it an overkill to have lots of classes? Suppose I define 4 interfaces each for create, r

Oop Designing WCF service interface. Procedural vs Object Oriented Design

we are building product that can be used by other systems. As we have SOA, we develop only a service (WCF). We had several controversial discussions about how to design an interface of that service. We are choosing between procedural and OO design for service. As our service will be used from .NET and Java some say that it is hard to integrate with service if it has OO design. Other think that services mast not use OO approach. Some say that OO is completely OK. As result we there is no clear d

Oop Data structure for grid with edge information

I want to implement a data structure of a grid of triangles shaped like this: |---|---|---| | / | / | / | |---|---|---| | / | / | / | |---|---|---| So every square cell is split in two triangle. The problem is that I need to store information for every edge of every cell. I thought about making a matrix of Object with every object containing 5 variables (4 edge + middle edge). But that means that there is redundancy because all edges are in common with some other cell. Or I could ma

Oop how do we create plugin / extensions in object oriented programming?

How does software allow developers to make a plugin / extensions on top of its core? How is that related to object oriented programming? maybe with inheritance or interfaces? What kind of design pattern should one use? For example, firefox extensions that enhance firefox, wordpress extensions, etc. Those systems sort of "recognize" plugins after being installed and work well and in some cases they perform safety checking, dependencies, and the like. Anyone care to shed light on this?

Oop Using Enums for Range Selection in OO Application

I am working on a project that has a large number of forms that users will be filling out to create a final report. A majority of these questions are multiple choice. I am struggling with the proper architecture to the classes within the application. For sake of conversation lets say this is an auto accident report. An object-oriented approach would dictate that we create structures based on the information contained in each question. So we have classes such as "Vehicle", "Accident", etc. But w

Oop How to package up test and normal implementations of a class

I am not quite sure if this question is relevant here; maybe it's too high level. Say I have an interface Foo which is implemented by two other concrete classes FooProduction and FooTest. The first one is the production code and the other one the test implementation. Now I want to package everything up but I am not sure which is more suitable. Moving the FooTest class in the test package (where I keep all my tests) or keeping Foo, FooProduction and FooTest in the another package, lets say the f

Oop VBA object's Collection property contains data but won't let me access it (get EOF/BOF error)

I have a class module in an Excel project that has a property called Marks, this is a VB Collection and has a public get property (but no set or let). I can assign values to this without any problem: myObject.Marks.Add 3.14159 However, when I try to do something with this object (e.g., iterating through it), I get an error: 3021: Either BOF or EOF is true or the current record has been deleted However, if I try myObject.Marks.Count, it shows that the collection contains the amount of data

Oop "Tell, Don't Ask" over multiple domain objects

Question How do I adhere to the "Tell, Don't Ask" principle when performing a function involving multiple objects. Example - Generating a Report I have the following objects (illustrative purposes only): Car, Horse, Rabbit There is no relationship between these objects, but I do want to generate a Report based on these objects: createHtmlReport(Car car, Horse horse, Rabbit rabbit){ Report report = new Report() report.setSomeField(car.getSerialNumber()) report.setAnotherFi

Oop Best practice for structuring data over time

Hypothetically, if I am tracking the work of a colleague over time. What is the best way to structure my data? My example is entirely made up, but it's a programming question that has come up in practice a huge amount of times. My question is best illustrated with a simple example : You are hardcoding your colleagues work into three separate lists every day. Let's say list 1 is "What he/she needs to do". Let's say list 2 is "What he/she has done". And finally, list 3 is the date these values

OOP; Class containing data

This isn't really a serious OOP question, just want to get an opinion on the best way to take for my program. Simple really: Let's say I have an employee class, and that class has the variables and methods that make up an employee. My question is how would I store an 'employee data'(Data, not Object); It IS SIMPLE, I could just make a JOHN class that extends EMPLOYEE and add data there. But I've read(actually not sure where) storing simple data in classes is not good?? Because if you extend a

Oop EIEIO Composition (exposing a slot of a contained object through own slot)

I have two EIEIO classes: (defclass i-driver () (;; more slots (exit-conditions :initarg :exit-conditions :initform nil :type list :documentation "Conditions to test in the main (while ...) expression")) :documentation "This class describes a single driver of `i-iterate' macro") and: (defclass i-spec () ((exit-conditions :type list :reader i--get-exit-conditions :documentation "Conditions to test in the main (while ...) expression") ;; more slo

Oop Using embedded classes to group related properties

Let's say I'm designing a Person class. Is it appropriate to use an embedded class to group similar properties of this person? For instance, let's a person has a weight, height, Hair color, and eye color. Instead of hanging these properties directly off of the person, what if I created a class called PersonPhysicalAttibutes that had these properties. So when you need to set a person's height, you'd use personA.PhysicalAttributes.Height = 6.1; Would you say this is a workable design? EDIT

Oop Multiple equations in one boolean statement

I think this is a really general programming question, since boolean syntax is more or less the same in a lot of common languages. But still my question is for php and javascript mainly. Suppose I want to write an if statement which returns true if a variable is equal to 2,3, or 5. And this variable has a very long name, so like this: if((An_Object_With_A_Long_Name.Has_Also_An_Array[With_An_Index_Too]==2) || (An_Object_With_A_Long_Name.Has_Also_An_Array[With_An_Index_Too]==3) ||(An_Ob

In OOP, how does persistence cooperate with object relations?

So in OOP, objects send messages to other objects. This is a pretty simple concept, and as long as all of the objects live in memory, it's easy to implement e.g. by calling methods. But in real life, we persist objects into the database or elsewhere, because there isn't enough RAM to hold all of them. How do you call a method on an object that is currently persisted? OK, so maybe unpersisting one object can be incapsulated into its Factory. But what if I want to send messages to a lot of objec

Oop Handling different UI behaviors based off different application states

I have an application that has a handful of states that all share a single UI. The thing is, depending on the application state, the components of the UI will be doing very different things. In one state, mousing over a component might bring up a tooltip, in another it might serve as a way to 'add to a list,' or some such behavior. For now, I have a single UI class with many component subclasses. The UI passes a callback to the components, which they might call when interacted with. As of now,

Oop Is it possible to apply the HATEOAS principle by SOA?

The question is theoretical. I found that the difference between resource oriented architecture and service oriented architecture is similar to the difference between object oriented programming and procedural programming. By resource oriented architecture the service (namespace) publishes resources (objects) on which I can call methods (methods). By service oriented architecture the service (namespace) publishes operations (functions) which I can call. By resource oriented architecture I can w

Oop How to call list of updatable

I have an interface, 'Updatable' which contains an 'update' method. I want to have a list of instances of this interface but am unsure how to name it. Is there a plural form of updatable?

Oop Best way to store different large matrices in Fortran

I need to store panel information of different bodies into matrices. Each matrix will contain all info for one body. So N bodies will leads to N matrices. However, the total number of bodies will be decided by user input. I am looking for a way to create the matrices separately. The for loop index-----i would be part of the matrix name so that the matrix size can vary depending on the specific body. The idea is like: for i = 1:N for j = 1: ROW for k = 1: COL

Oop Passing "type" argument to functions

Is it possible to pass a type argument to function so that create_eclass* function can only be written once by passing class type argument to it ? class bclass; virtual function void print(); $display("Base Class"); endfunction endclass class eclass1 extends bclass; function void print(); $display("Extended Class1"); endfunction endclass class eclass2 extends bclass; function void print(); $display("Extended Class2"); endfunction endclass program Test

Lua OOP not finding variables

I'm trying to do OOP in Lua, but it's not letting me change the vel_y value in the checkInput{} method. Any ideas how i can get this to work? By the way I'm using Love2D for this input stuff. Player = {x = 100, y = 20, vel_x = 0, vel_y = 0} function Player:new(o, x, y, vel_x, vel_y) o = o or {} -- create object if user does not provide one setmetatable(o, self) self.__index = self length = 0 return o end function Player:getX() return self.x end function Player:getY()

Oop How can I create two new figures in matplotlib using python and then update them in subsequent code?

I have some python simulation code that runs for a minute or two and displays the output of the simulation in real-time. I would like to show results on two different figure windows. Because I'm using an object oriented design, it's a little difficult to switch between the figures using the figure(x) command, so I want to save a reference to each figure to each variable and use that to return to them. I've set it up like the following: import pylab as p f0 = p.figure() f1 = p.figure() ax0

Oop When and how to assign unique id to an entity in DDD?

The best example would be an User entity which needs to be persisted. I have the following candidates to assign unique identifier to an user: Assign keys provided by back-end (NDB, MySQL etc.). Hand crafting unique identifier through some service (like system clock). Properties like emailId. Taking a simple example of a detailed view, we often have a detailed display of an user like some/path/users/{user_id}, if we keep emailId as the unique id then there are chances that an user may change

Oop setting/getting object's property value directly or by method?

This is more general question to any OOP, please before answer consider readability and efficiency. Here is example in Javascript: function fnc () { this.var = "abc"; this.setVar = function (val) { this.var = val; } this.getVar = function () { return this.var; } } Now, i can set value of var via method: fnc.setvar("abc"); or fnc.var = "abc"; I can also get it directly: console.log(fnc.var) or via get method: console.log(fnc.getVar()) Here comes the

Oop How can i return different types from my method?

I have a method which returns an object (this._response) which is of type IResponse. I want to return this._response.details which is of type IDetails. get response(): IResponse { if (this._response.response.header.statusCode === "0000" || this._response.response.header.statusCode === "YHOO") { return this._response.details; //IDetails } else if (this._response.response.header.statusCode === "6621" || this._response.response.header.statusCode === "6622") { this._response

Oop How to refactor these classes to interact each other?

My requirement is to use the name of the shape and draw that shape with the dimensions like in the method Draw('rectangle', 'l:10,w:20');. There should be validation of the dimensions against the type of the shape. These classes can be refactored to add more classes or change the hierarchy. No run-time checking like reflection should be used. The problem needs to be solved with class design only. Don't use if-else or switch statements in the client method Draw. Requirement: public static

Oop Implementing deep clone()

Consider some OOP language (doesn't really matter which one is it) and suppose the language creator would like to add a deep clone() method for every class. Also, it is given that the heap is implemented as a tree. How should the language creator implement it? So basically we can (automatically, at compilation time) implement a clone() method and adding it to the proper functions virtual table. It will malloc() the proper size which is known in run-time and copy from source to destination

Oop Code refactoring: two but not all the derived classes of a base class have an identical override method

In C#, a class B serves as the only base class of three classes C, D and E. B has a virtual method, which is overridden in C, D and E. C and D have the same implementation of the override method, different from the one in E. C and D don't have other things in common. How can I remove code duplicate between C and D? Two ways that I am considering are: create a new class F derived from B and make C and D derived from F instead of B. Move the common override method in C and D to F. I think i

State machines, encapsulation and OOP design

I'm implementing a FSM using Boost's MSM library. In the FSM, I have transition tables which describe Events, Source states, Target states, Actions and Guards. It's my first time using a higher-level design of a state machine. In the past, I've just used switch statments and executed code. However, this one is going to be big and I wanted to keep everything organized properly so it doesn't turn into a mess. I have an object that represents the state machine (it's a boost::msm::back::state_m

Execute a method when object is changed (OOP)

I'm learning OOP and trying to write a simple program that will execute some method every time when a specific varible will change. I have two classes: public class SomeClass { private OtherClass object; public OtherClass getObject() { return this.object; } public void setObject(OtherClass object) { objectChanged(); this.object = object; } private void objectChanged() { System.out.println("Object has changed"); } } public class OtherClass { private int val

Oop How to design class property containing a collection of translations? For patterns gurus

I am design pattern newbie, please help to properly organize classes. My entity has a property 'name' that should have several translations: class Entity { private int id; private TranslationCollection name; ... } 'name' - should contain a set of translations: { 'en': 'english word', 'sp': 'spanish word', ... } So I decided to make class 'Translation': class Translation { private string locale; private string value; public constructor (locale, value) { ... } ... }

Oop How to implement an abstract class in Go?

How to implement an abstract class in Go? As Go doesn't allow us to have fields in interfaces, that would be a stateless object. So, in other words, is it possible to have some kind of default implementation for a method in Go? Consider an example: type Daemon interface { start(time.Duration) doWork() } func (daemon *Daemon) start(duration time.Duration) { ticker := time.NewTicker(duration) // this will call daemon.doWork() periodically go func() { for {

Oop PHP 7.4 Typed property with floats / doubles

I apologise in advance if this is a lame question, Its my first. I am building a small framework for a university project and I wanted to enforce types as much as possible, Great to see now that PHP 7.4 has strict types for properties, But it is not being properly enforced even with declare strict_types. Also on a side note, I know people say in PHP there is no difference between doubles and floats, but with typed properties, PHP does not recognise double as a data type. See the simple code test

Oop What design pattern to use for instantited objects containing permutations of a string?

I would like to know if there is a design pattern to cover making multiple objects representing mutiple permutations of a string. For example: I have a database table containing item names. Each item has a sort of "signature" (can't think of a better word for it), which is all the letters of the item name, sorted in alphabetical order with the spaces removed. Given a "soup string" of jumbled up letters, I would like to sort those letters in alphabetical order to match it to a

Oop Problem with changing the value of main button in KivyMD Menu

I have created a KivyMD Menu. When I click on the main Button, the menu is opening without a problem. However when I click on a menu button the value of the main button is not changing. Nothing happens. I thought the code is sufficient to achieve it. Does anyone know a solution? Thank you in advance! py file: from kivy.core.window import Window from kivy.uix.screenmanager import Screen from kivy.lang import Builder from kivymd.app import MDApp from kivymd.uix.menu import MDDropdownMenu Window.

Oop Logic behind plugin system?

I have an application in PHP (private CMS) that I would like to rewrite and add some new things - I would like to be able to extend my app in an easier way - through plugins But the problem is - I don't know how to achieve "pluggability", how to make system that recognizes plugins and injects them into the app? So, what's the logic of a simple plugin system?

Oop Is it poor design to have a class used only by one other class?

I have a QueueProcessor class that processes a work queue. I want to send an email out of a summary of all work done with a bunch of statistics. I am already using a mail class (Zend_Mail), so most of the email work is abstracted away for me, but I still have to figure out where to put the code to generate the summary information. I'm basically collecting data during the processing and then I have to transform the data into a format suitable for email. My question is, should I create a separate

Oop General OO design pattern

Consider the following general program structure: Class A has an instance of Class B as a member variable Class B has a collection member variable containing instances of class C Events in class A are propagated to the C instances by A simply telling B about the event What are the design patterns concerning instances of class C talking back to class A? One option is instances of class C posting notifications to which class A subscribes. Another option is passing a reference to class A "down

Oop Can I dynamically call a local function?

I have a module that looks like this. I've simplified it greatly so as not to clutter up my question (my local functions are more complex than this). Here is my code: decision = {} function win(win_arg) return win_arg end function lose(lose_arg) return lose_arg end local function draw(draw_arg) return draw_arg end function decision.get_decision(func, arg) return func(arg) end return decision I am calling my module with the code below. my = require "my-lua-script" print(my.get_decisio

Oop Provide access to instance in event handler

For now, I'm trying to learn dart language, and stuck with a problem. Firstly, some code. _clickHandler and _constructNode are method of same class EventListener _clickHandler = (Event e){ this.setActive(e.currentTarget); }; /* Render methods */ Element _constructNode(Node node){ DivElement nodeContainer = new DivElement(); nodeContainer.id = "node-${node.id.toString()}"; nodeContainer.classes.add("node"); SpanElement nodeTitle = new SpanElement();

Oop Getting rid of an instance of a class in Lua

I am currently trying to do OOP in Lua. From what I've understood here, the instance of a class and even the class ( the variable ) itself are a reference to the various bits and bobs the class holds, so if I have a method :destroy(), consisting of function class:destroy() self = nil end when I call instance:destroy() the reference instance should be picked up by the garbage collector and practically, the instance as in an object is gone. It won't throw up an error or slowly cause a memory

  1    2   3   4   5   6  ... 下一页 最后一页 共 23 页