Nobody
Nobody

Reputation: 4841

Avoiding many inheriting classes

Lets say I have this class (just as an example):

internal class Packet
{

    private readonly UInt32 _length;
    private readonly Byte _type;
    private readonly UInt32 _requestId;

}

There are many different types of packets each of which inherit from this class and each packet type can have any number of properties of varying types.

Is there a way to implement every type of packet without using inheritance?

I thought about using a property such as List<Tuple<Type,Value>> _typesSpecificValues - I know it won't compile but I don't know how else to express what I mean.

I need to avoid creating an inheriting class for each type of packet because there are about 50 types - or am I just being lazy??

Upvotes: 2

Views: 166

Answers (4)

Carlos Mu&#241;oz
Carlos Mu&#241;oz

Reputation: 17824

If you have so many different types of classes with many diverse caracteristics between them you should not use inheritance but instead you should use Composition.

Read this article that explains it way better than I could.

EDIT

Read this even better chapter about the decorator pattern from the excellent book Head First: Design Patterns

To make sure I get you attention to this book here there are some screenshots:

Inheritance Inheritance

Composition Composition

Upvotes: 1

Beep beep
Beep beep

Reputation: 19171

What you need to ask yourself is: does is make any sense to use 'Packet' by itself?. Will you be accessing the base class's properties in all/most uses?

For example, let's say you have:

public class CommPacket : Packet
{
    public string Message { get; set; }
}

Would it be typical to access CommPacket.Length? Or would it ever make sense to pass a CommPacket to some class that accepted a Packet as a parameter? If the answer to either of these is Yes, you should be using a base class.

Upvotes: 1

Beth Lang
Beth Lang

Reputation: 1905

Based on your brief description it sounds more like they should be structs instead of classes. Take a second look at your 50+ different definitions and try to see what is really different about them. For example, if half get processed one way and half another maybe you really just have two classes that know how to deal with the different structs.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502336

It sounds like you should be creating separate classes, yes.

However, I'm not sure whether I'd make them derive from this class. It sounds like this should be in a Header class (or possibly even a struct) and then you could have multiple classes which each contain a Header.

Upvotes: 7

Related Questions