Skip to main content

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
2 votes
4 answers
606 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, ...
20 votes
5 answers
7k views

Inheritance vs mixins in dynamic languages?

When should you prefer inheritance patterns over mixins in dynamic languages? By mixins, I mean actual proper mixing in, as in inserting functions and data members into an object in runtime. When ...
66 votes
11 answers
65k views

In Object-Oriented Programming, why is it generally desirable to split a program into multiple classes? [closed]

After studying Programming through books, they have taught me concepts such as inheritance, but never explain how splitting a program into multiple classes helps with anything. Yet, many books seem to ...
2 votes
2 answers
265 views

Is it ok to extend utilities?

Apache Commons has StringUtils. It's great, but I wish it had a shuffle() method or similar Is it ok to create my own StringUtils that extends Apache's StringUtils and adds the method (Apache's class ...
2 votes
3 answers
232 views

"use auto" and "declare most abstract type", which guideline has higher priority?

According to Why define a Java object using interface (e.g. Map) rather than implementation (HashMap), I know I should declare most abstract type when possible, for example, suppose I'm using an UI ...
0 votes
2 answers
103 views

Modeling value object when fields' existence depends on state of other fields

I am practicing tactical DDD and having trouble as exemplified below. Fundamentally, whether some fields of the value object should be nullable depends on another field of the same value object. ...
5 votes
2 answers
725 views

Is "using active record pattern" a reason to inherit from standard container (eg:vector)?

According to Is it bad practice to use Inheritance to associate methods with a basic container?, I know it is bad to inherit form std containers, mainly because std containers are not designed to be ...
1 vote
3 answers
228 views

In "Liskov Substitution Principle", is "invariants can't be weakened in a subtype" a kind of "postconditions can't be weakened in a subtype"?

According to Invariant rule in Liskov Substitution Principle, I know one of the form of violation of "Liskov Substitution Principle" is violating "invariants can't be weakened in a ...
5 votes
4 answers
2k views

If class B extends A, can we say that B depends on A?

Let's say we have 2 (Java) classes: class A {} class B extends A {} To me, saying B extends A and B is dependent on A are both true (but not equivalent) in this situation. My colleague, OTOH, says ...
62 votes
8 answers
28k views

LSP vs OCP / Liskov Substitution VS Open Close

I am trying to understand the SOLID principles of OOP and I've come to the conclusion that LSP and OCP have some similarities (if not to say more). the open/closed principle states "software ...
20 votes
1 answer
1k views

Why does(/did) Bertrand Meyer think subclassing is the only way to extend a "closed" module?

In Meyer's Object-Oriented Software Construction (1988) he defines the open/closed principle as follows: A module will be said to be open if it is still available for extension. For example, it ...
3 votes
1 answer
284 views

Object-oriented programming design with relational database tables

I want to understand what is considered best-practice to better align with OOP when handling relational databases. I cannot find any online examples where classes and a more maintainable/re-usable ...
1 vote
1 answer
189 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 ...
-2 votes
3 answers
191 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 ...
1 vote
4 answers
779 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 ...
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 ...
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/...
4 votes
6 answers
2k views

Inheritance best practice?

I'm fairly new to object oriented programming and have a question I've stumbled upon regarding inheritance best practice. I'm building a system for weapons in a game. I have a base class called ...
0 votes
5 answers
2k 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 ...
1 vote
2 answers
285 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 ...
5 votes
2 answers
2k views

How to maintain encapsulation with composition in C++?

I am designing a class Master that is composed from multiple other classes, A, Base, C and D. These four classes have absolutely no use outside of Master and are meant to split up its functionality ...
0 votes
1 answer
1k 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?
0 votes
2 answers
354 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 ...
1 vote
5 answers
677 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 ...
2 votes
2 answers
144 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{ ...
2 votes
2 answers
396 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 ...
0 votes
2 answers
202 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 ...
7 votes
5 answers
28k views

What is good practice when inheriting static classes isn't possible/allowed

I am developing a project in C# and due to a design decision it is not possible to have a static class inherit another static class. But I have, in my opinion, a case where this would make sense. I ...
2 votes
2 answers
419 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 ...
0 votes
0 answers
49 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 ...
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 ...
0 votes
2 answers
1k 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 ...
0 votes
0 answers
518 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 ...
2 votes
2 answers
259 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 ...
1 vote
1 answer
185 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 ...
0 votes
1 answer
100 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 ...
-1 votes
3 answers
560 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 ...
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 ...
0 votes
1 answer
283 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 ...
2 votes
2 answers
210 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 ...
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 ...
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 ...
4 votes
5 answers
19k views

Why we use virtual and override keywords in c#

Can anyone explain me what's the point of overriding base class implementations (if its not abstract), because it's not ethical move to modify features of the parent class according to the wishes of ...
12 votes
9 answers
4k views

How can designing for inheritance cause extra cost? [closed]

So I wanted to inherit from a sealed class in csharp and got burned. There is just no way to unseal it unless you have access to the source. Then it got me thinking "why sealed even exists?". 4 ...
-1 votes
1 answer
702 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 ...
0 votes
2 answers
1k 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 ...
14 votes
4 answers
15k views

Can a method that must be overridden be considered private?

Suppose I have a class C with a method f() which is meant to be used only within C's implementation, but which should be overridden by C's subclasses. Is it reasonable, or "pythonic", to consider it ...
0 votes
3 answers
783 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, ...
0 votes
1 answer
2k views

Inheritance and association relationships in UML

I was creating a class model using inheritance, and have a situation I don't know how to represent. For this question I built an example diagram in which I have a class Person with some attributes. I ...
-3 votes
3 answers
385 views

OOP and class that inherit from many classes

In OOP, is it possible to have a class that inherits from multiple other classes? And if yes, how is this situation called? For example, suppose I have the following classes: Eye Nose Mouth Eyebrow ...

1
2 3 4 5
12