Skip to main content
Share Your Experience: Take the 2024 Developer Survey

Questions tagged [inheritance]

Inheritance is a way to reuse code of existing objects, or to establish a subtype from an existing object, or both, depending upon programming language support.

Filter by
Sorted by
Tagged with
1 vote
1 answer
145 views

Inheriting a logger

When you define a class, is inheriting a logger such as log4cxx a good design? Assume I am defining a class called MyClass. When I want a logger, I use a pointer to an abstract logger class as a ...
Dhammika Wijesundera's user avatar
-2 votes
3 answers
173 views

Class inheritance design with protected methods and run time base handlers

Using C#, I got a class called BaseConfigurations which handles CRUD operations. This class also contains a protected method which is used inside the CRUD handling methods: public class ...
CodeMonkey's user avatar
1 vote
4 answers
415 views

What's the alternative to trying to inherit static methods?

I know you can't inherit static methods, and it seems the consensus is that if you feel like you need to, you're doing something wrong. However, I don't know what the alternative is in my case. Please ...
Andrew Dean's user avatar
24 votes
11 answers
8k views

Is it logical to not use inheritance because the function is critical?

Our codebase has a typical base-class with a ton of sub-classes. The base-class already has many default functions for the sub-classes. However, one particular function has the same verbatim ...
Zack Light's user avatar
0 votes
5 answers
584 views

Comparing Java objects with different member variables

I have a base class "People" which two other classes inherit from: Employee and Student. The Student class includes a GPA (type double) and the Employee class does not. I have an ArrayList ...
Delta88's user avatar
  • 19
0 votes
1 answer
720 views

Why are sealed classes not allowed to be mocked?

Using Moq framework, it is not allowed to mock a class in C# which is sealed. Same goes for many other frameworks as well. But why is it not allowed?
Akshunya's user avatar
  • 111
0 votes
2 answers
298 views

Does Clean Code suggest avoiding all base class instance variables (include private instance variables)?

According to Why is Clean Code suggesting avoiding protected variables?, I should avoid protected variables because of the reason : "closely related concepts should not be separated into ...
wcminipgasker2023's user avatar
1 vote
5 answers
554 views

How does inheritance lead to higher coupling than composition?

One major reason for using composition over inheritance is, that inheritance leads to higher coupling. How is that? In both cases members are exposed to the subclass (in case of inheritance) or ...
cobby's user avatar
  • 119
2 votes
2 answers
141 views

What is the threshold of "usage" of a parent class member that should move to child class?

For example, for base and child classes, if all child class need a class member, eg: baseHp, which represents the base hp to calculate the actual hp of monsters in a game: public class Monster{ ...
wcminipgasker2023's user avatar
2 votes
2 answers
328 views

In "Liskov Substitution Principle", are "Preconditions can't be strengthened in a subtype" & "Postconditions can't be weakened in a subtype" the same?

According to Is this a violation of the Liskov Substitution Principle?, as I understand, the top answer currently says the code below is violating "Liskov Substitution Principle": public ...
wcminipgasker2023's user avatar
15 votes
6 answers
6k views

Why is it necessary to mark classes as not inherited from? Can't an optimizer automatically detect that virtual calls are unnecessary?

In C# and C++, an apparent trend is in place to reduce / avoid inheritance: C#: "Sealing types can improve performance." https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/...
user avatar
0 votes
2 answers
196 views

For non-container classes, are "better naming" and "ready for commented codes" good reasons not to declare the most abstract type?

According to Why define a Java object using interface (e.g. Map) rather than implementation (HashMap), I know I should declare the most abstract type possible, but the question is about template class ...
wcminipgasker2023's user avatar
2 votes
2 answers
321 views

Composition over inheritance: how data are accessed in the composition case?

I've been reading this Wikipedia article Composition over inheritance. It gives a code example of inheritance first, and then a code example of composition. In case of inheritance there are data that ...
Andrew Savinykh's user avatar
0 votes
0 answers
48 views

Should I add new method to the interface to use it more commonly or just separate the new logic completely

I have a CouponReservationService in an e-commerce project. It is called when a coupon is reserved to be applied to a basket. It checks that whether the coupons are already reserved. If they are ...
Ismail Yavuz's user avatar
0 votes
0 answers
372 views

What is the Best Practice for handling multiple Entities that behave identically?

Because I have multiple entities with unique fields, I need multiple repositories for each one even though each Entity will be handled exactly the same. What is the best way to handle these separate ...
dbrewster's user avatar
  • 139
2 votes
2 answers
198 views

Pattern for a base class to do pre-validation and/or post-processing on a deriving class's overridden method?

I have the following pattern repeating itself in multiple places: abstract class Database { void connect() { this.setStatus( CONNECTING ) try { await this.realConnect() } catch ...
Markus Meskanen's user avatar
1 vote
1 answer
160 views

Is it an acceptable pattern to put derived classes inside an abstract base class in Java?

Suppose I have some Java code such as the following (in this case, the use of the name "interaction" is referring to interacting with an object in a video game): public abstract class ...
micheal65536's user avatar
0 votes
1 answer
95 views

How to refactor parallel inheritance tree?

I have a (php) program, which must change yearly. This program calculates tax for every year and there are sometime changes in requirements. First, the user fills their incomes, expenses, etc. Then ...
nrob's user avatar
  • 111
-1 votes
3 answers
357 views

Is it better to override methods in classes or make methods general?

I am creating the backend of a microservice that will serve as a tool to see in real time how the company's employees are distributed by projects and what days they have assigned to each one. The ...
Diegol's user avatar
  • 1
0 votes
1 answer
234 views

Exposing only the getters of a singleton interface in C++

I've got a file in my includes folder, which is the folder I expose, that isn't used externally and isn't supposed to be used too. When I noticed that and tried to remove it - I noticed that it's ...
RedYoel's user avatar
  • 123
2 votes
2 answers
194 views

Explain forbidden inheritance across the domain dimensions of representation/implementation vs semantics

I am going through this nice write up on thoughtworks about inheritance vs composition. I understood the authors explanation of the dual purpose of inheritance. But, I am confused on the specific ...
kosa's user avatar
  • 159
16 votes
6 answers
6k views

Why can't a mutable interface/class inherit from an immutable one?

I've heard people say things like "B can't inherit from A because A is immutable and B is mutable". My understanding of inheritance in Object-Oriented Programming is that you use it to add ...
GlenPeterson's user avatar
  • 14.9k
21 votes
6 answers
6k views

Does subclassing int to forbid negative integers break Liskov Substitution Principle?

In Python 3, I subclassed int to forbid the creation of negative integers: class PositiveInteger(int): def __new__(cls, value): if value <= 0: raise ValueError("value ...
swoutch's user avatar
  • 321
-1 votes
1 answer
610 views

What is the use of Multiple Inheritance in languages like C++ and Python?

C++ and Python are the only two languages I know supporting multiple Inheritance. Other object oriented languages I have seen like Java and Ruby do not support multiple inheritance. Even the front-end ...
Arunabh Bhattacharya's user avatar
3 votes
3 answers
416 views

Large Inheritance Hierarchy vs. One Object With Many Nullable Fields

I am working on implementing some stock order types for a financial technology application. There are six different types of stock orders - market, limit, stop_loss, stop_loss_limit, trailing_stop, ...
Treker's user avatar
  • 199
0 votes
2 answers
895 views

Inheritance/Composition VS "Direct Injection Construction"

my following example seems to go into the direction Inheritance VS Composition. But that's not, what i want to ask. I see the concept Inheritance and Composition on one side and the alternative, which ...
Robin Kreuzer's user avatar
0 votes
3 answers
451 views

How to handle subclasses needing different method signatures for the overriden function?

I have an abstract class that represents chess pieces, it has an abstract method isMoveValid(Square futurePosition, PieceColor color) which checks if the piece moving to that square is valid or not, ...
Yoh's user avatar
  • 51
2 votes
3 answers
416 views

Object Oriented Programming - what is the best way to add new parameters?

I have a doubt about what would be the right OOP approach for implementing classes that do similar stuff with different parameters. To provide a simple example, I would use two polynomial classes, ...
ThePunisher's user avatar
2 votes
4 answers
276 views

Database design - how to model database tables for similar objects - booleans / enums / inheritance / archived vs active

I only recently started to work with backends. My database is supposed to store information about maven-like artifacts. There are going to be applications and configuration artifacts. Now those ...
Marcin K.'s user avatar
  • 129
1 vote
2 answers
239 views

How to design relationships with constraints on subclass type?

I'm developing a full-stack Rest application following a narrative description of a working context. There is a class Job with two subclasses Job_A and Job_B. Job_A produces Report_A while Job_B ...
Wippo's user avatar
  • 119
50 votes
7 answers
10k views

Why is inheritance bad in a Person-Student model?

I've just started learning about Inheritance vs Composition and it's kind of tricky for me to get my head around it for some reason. I have these classes: Person class Person { public string Name {...
Octavian Niculescu's user avatar
8 votes
4 answers
2k views

Are there any legitimate use cases for protected visibility?

Protected visibility in languages like C++, Java or PHP is a strange beast: it makes fields and methods accessible in subclasses, but not in code completely outside the class. It strikes me as ...
user3840170's user avatar
2 votes
3 answers
868 views

Should classes with business logic inherit from a class with helper methods, or vise-versa?

I have a codebase where some classes contain both "essential" business logic, and "incidental" complexity. I am considering a refactor where I leverage inheritance to improve the ...
MYK's user avatar
  • 343
-1 votes
2 answers
151 views

Is an abstract role needed to ensure that a customer can only have one role out of several? [closed]

I have the following UML class diagram in a C++ context. I want to make sure that a Customer can have only one role: Can the Customer now only assume one role, and what does <<abstract>> ...
Seonix's user avatar
  • 11
0 votes
2 answers
890 views

How to concretize a return type when inheritance is used?

I have two repositories: class RepositoryOne { /** * @param int $id * @return ModelOne */ public function getById($id) { // Search and find a ModelOne model in the ...
pro100tom's user avatar
  • 449
0 votes
2 answers
426 views

How to solve an issue when a decorator needs variables from the base class?

I have a service class that does some magic. I want to introduce a new type of functionality - raise an event. I am absolutely sure that decorator pattern is great for this scenario. The problem is ...
pro100tom's user avatar
  • 449
3 votes
2 answers
1k views

Is inheritance constraint on Generics redundant? If not what is its recommended use?

I've recently found myself using a generics with constraint that a type should inherit from a specific base class, but now I've just realised that this is redundant and unnecessary because the ...
Piotr Golacki's user avatar
5 votes
2 answers
1k views

Design classes to model 3D scanned faces of ancient Greek/Roman sculptures: is multiple inheritance a good design solution?

I would like to deepen the topic of multiple inheritance using Python and I usually find examples that are too simple. I love art and I imagined the following problem and I want to understand if ...
blunova's user avatar
  • 398
0 votes
1 answer
232 views

Wrapping the UI framework

I want to write an application where I would delegate certain functionalities to 3rd party libraries. To make sure the code remains modular, I want to put these libraries behind an interface so I can ...
yah_nosh's user avatar
-1 votes
1 answer
647 views

Subclasses with same behaviour but different attributes for different inputs

Say I have two object types of the same interface MyObj (I am using python in this project so I will use the same for the explanation) class Foo(MyObj): a = [5, 10] class Bar(MyObj): a = [[1, ...
doca's user avatar
  • 175
4 votes
5 answers
434 views

Single Responsibility Principle, Inheritance

I have the following interface: class IHittable { virtual Intersections intersects(const Ray & ray) = 0 } which will be implemented by various geometric objects(Spheres, Triangles etc). Now ...
a a's user avatar
  • 261
9 votes
6 answers
3k views

Composition over inheritance when adding functionality to a foreign object

Note: I am not sure of the correct terminology for what I am describing, so if you have suggestions for a better title please feel free to edit it. "Favor composition over inheritance" is ...
Asad-ullah Khan's user avatar
2 votes
2 answers
208 views

How would dispatch work in the Wizards and Warriors "rulebook"?

In Part 5 of Wizards and Warriors, the blog proposes the concept of a "Rule" and rulebook to address the issues with solutions in the previous parts. One of the issues was the need for ...
justin's user avatar
  • 49
1 vote
4 answers
746 views

Is casting between interfaces the best approach for capability discovery when using interface inheritance?

It’s frequently taught that downcasting is bad practice. I have a case where it seems necessary, but I’m wondering if there is an alternative way to design this. Suppose interfaces are kept small ...
justin's user avatar
  • 49
1 vote
1 answer
215 views

How do I ensure that only service models are used as properties?

I work on a system that utilizes a form of n-tier architecture in that we have data and service models. The service models derive from the data models: public class FooDataModel { public int ...
Hazel へいぜる's user avatar
2 votes
4 answers
2k views

Confused about inheritance and correct usage. Should I avoid using members in base class?

I am using C++ , but as far as I understand most OO principles are cross language. In most of the articles that I have read and liked about inheritance the advice are about : not to use it for the ...
user3717741's user avatar
1 vote
2 answers
783 views

Concept/Design question: Alternatives to switch/conditional statements and Enums

I am practicing design patterns and OO concepts such as inheritance in java and I'm writing an application that represents a vending machine. I have two questions focused on ideal structure and design ...
Bob Jones's user avatar
6 votes
9 answers
2k views

Java instanceof and Clean architecture

It seems to me that there is a conflict between clean architecture and the recommendation not to use instanceof. Consider the following code: class ParentEntity { } class AEntity extends ParentEntity ...
Shayan's user avatar
  • 199
2 votes
3 answers
162 views

Java design: there is two interface: B extends A. A and B have one subclass each, named ABase and BBase, can I make BBase extend ABase?

there is two interfaces A and B: public interface A { } public interface B extends A{ } A and B have one subclass each: public abstract class ABase implements A{ } public abstract class BBase ...
Guo's user avatar
  • 177
0 votes
1 answer
52 views

Select inheritance hierachy at run time

I want to model a machine with a class machine. By the way the architecture of the project has been built, the module that defines each machine is its own directory. So in directory manufacturer/...
TeXtnik's user avatar
  • 101

1
2 3 4 5
12