Should a specific proportion of members be shared between base and derived classes? - class-design

I'm currently designing the classes for an application I'm writing for my coursework, and I have two classes that sound as if they should be a base-derived class pair, and do indeed share two member variables, and my problem is that they each have seven member variables and no operations.
The reason for the structure of these classes is that I am building a RSS reader and I intend to have these two classes hold data on the feeds. The first one will hold the data on the feed itself, for example the source url, the location of the rss.xml file on local storage, when the feed was last updated, etc. The second will hold information on the articles contained within the feed such as the publication date/time and an integer index based on the publication date that will be used to chronologically sort the articles.
class feed
{
string title;
string description;
string feed_url;
string local_location;
string channel;
bool feed_is_changed; // This is a flag that will be raised and lowered
// when the feeds are being refreshed
double last_updated; // The last update date/time will be converted to a
//standardised double value
}
class feed_item
{
string title;
string description;
double pub_time;
double pub_time_in_sec; // I'm separating the seconds so they can be used
// for a 'sub-index' when there are multiple feeds with the same pubtime
// (there are restrictions on the data types we are allowed to use
// (concocting work-arounds will aid in understanding, etc))
double pub_date;
int pub_year;
int order_in_list; // The index that will be calculated from pub_time,
// pub_date, etc
}
The above code is not complete, I'm currently only identifying variables and functions, and the private/public bits will come once they're finalised. As you can see from the above code, the only two variables that are being shared are title and description.
I'm not sure if it's worth making them an entity-base pair and just deactivating the five irrelevant variables, if it's more efficient to just make them completely separate classes, or if this is an entirely situational concern, and that it can be argued either way. My concerns are that the code may become difficult to both maintain and scale, but that there may be execution overhead inherent in one method or the other. Any thoughts and advice on this would be most appreciated.

A feed_item isn't a feed, so it fails the Liskov substitution principle and shouldn't be a subclass. I should check your ears — this pair of classes absolutely doesn't sound like they should be subclasses.
Occasionally (very, very occasionally) implementation inheritance is a good idea, but it's usually better done by extracting shared parts into a separate class and using it in both implementations. Here, it's absolutely a terrible idea — there's no great sharing of code, so the benefits are at best vague. Keep your code simple!

Just one derived class? Then almost certainly inheritance is the wrong design.
Inheritance is limiting, and those limits often don't appear until later making the decision even more expensive.
My rule of thumb is to avoid inheritance unless and until I can make a clear and compelling case to use it.

If you really wanted a base class:
struct NamedItem { // or maybe just "Item"
string title;
string description;
};
struct Feed : NamedItem {/*...*/};
struct FeedItem : NamedItem {/*...*/};
Or, usually preferred and a better fit in this case, use containment:
struct ItemInfo {
string title;
string description;
};
struct Feed {
ItemInfo info;
//...
};
struct FeedItem {
ItemInfo info;
//...
};
In particular, if you have no idea how you'll use a "NamedItem" without knowing the most derived type, it doesn't make sense to use inheritance.

Related

Difference between getter and accessing it directly

For example I have a field that I want to access in my app view. I have this provider
class User with ChangeNotifier{
String userNick = "test";
String get getName() => userNick;
}
What will be the difference, if I access the nick this way in my app vs getter?
context.watch<User>().userNick;
vs
context.watch<User>().getName();
If I don't use the getter and my userNick changes, will I not see it refreshing in my app or?
Getters/setters are preferred for use the data properly. If you use the data directly, you can update it when you even don't wanna update it and this type of logical mistakes takes too much time to detect and fix. Also, it is safe way to manipulate the data.
Encapsulation is an object-oriented programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
from: https://en.wikipedia.org/wiki/Object-oriented_programming
For more, you can search for encapsulation online.

Grouping constants within a class c++ [duplicate]

I have a whole bunch of constants that I want access to in different parts of my code, but that I want to have easy access to as a whole:
static const bool doX = true;
static const bool doY = false;
static const int maxNumX = 5;
etc.
So I created a file called "constants.h" and stuck them all in there and #included it in any file that needs to know a constant.
Problem is, this is terrible for compile times, since every time I change a constant, all files that constants.h reference have to be rebuilt. (Also, as I understand it, since they're static, I'm generating a copy of doX/doY/maxNumX in code every time I include constants.h in a new .cpp, leading to kilobytes of wasted space in the compiled EXE -- is there any way to see this?).
So, I want a solution. One that isn't "declare constants only in the files that use them", if possible.
Any suggestions?
The only alternative is to make your constants extern and define them in another .cpp file, but you'll lose potential for optimization, because the compiler won't know what value they have when compiling each .cpp`.
By the way, don't worry about the size increase: for integral types your constants are likely to be inlined directly in the generated machine code.
Finally, that static is not necessary, since by default const global variables are static in C++.
You declare them as extern in the header and define them in an implementation file.
That way, when you want to change their value, you modify the implementation file and no full re-compilation is necessary.
The problem in your variant isn't compilation-related, but logic related. They will not be globals since each translation unit will have its own copy of the variable.
EDIT:
The C++-ish way of doing it would actually wrapping them in a class:
//constants.h
class Constants
{
public:
static const bool doX;
static const bool doY;
static const int maxNumX;
}
//constants.cpp
const bool Constants::doX = true;
const bool Constants::doY = false;
const int Constants::maxNumX = 5;
I think your base assumption is off.
Your other headers are usually organized by keeping together what works together. For example, a class and its related methods or two classes heavily interlinked.
Why group all constants in a single header ? It does not make sense. It's about as bad an idea as a "global.h" header to include every single dependency easily.
In general, the constants are used in a particular context. For example, an enum used as a flag for a particular function:
class File {
public:
enum class Mode {
Read,
Write,
Append
};
File(std::string const& filename, Mode mode);
// ...
};
In this case, it is only natural that those constants live in the same header that the class they are bound to (and even within the class).
The other category of constants are those that just permeate the whole application. For example:
enum class Direction {
Up,
Down,
Right,
Left,
Forward,
Backward
};
... in a game where you want to express objects' move regarding the direction they are facing.
In this case, creating one header file for this specific set of constants is fine.
And if you really are worried about grouping those files together:
constants/
Direction.hpp
Sandwich.hpp
State.hpp
And you will neatly sidestep the issue of recompiling the whole application when you add a constant... though if you need to, do it, you're paying the cost only once, better than a wrong-sided design you'll have to live off with for the rest of your work.
What is the problem with this usage?
Do not declare a static type in header file, It does not do what you think it does.
When you declare a static in header file a copy of that variable gets created in each Translation Unit(TU) where you include that header file, SO each TU sees a different variable, this is opposite to your expectation of having a global.
Suggested Solution:
You should declare them as extern in a header file and define them in exactly one cpp file while include the header with extern in every cpp file where you want to access them.
Good Read:
How should i use extern?
Another approach which is best for compile times (but has some minor run-time cost) is to make the constants accessible via static methods in a class.
//constants.h
class Constants
{
public:
static bool doX();
static bool doY();
static int maxNumX();
};
//constants.cpp
bool Constants::doX() { return true; }
bool Constants::doY() { return false; }
int Constants::maxNumX() { return 42; }
The advantage of this approach is that you only recompile everything if you add/remove/change the declaration of a method in the header, while changing the value returned by any method requires only compiling constants.cpp (and linking, of course).
As with most things, this may or may not be the best is your particular case, but it is another option to consider.
The straight forward way is, to create non const symbols:
const bool doX = true;
const bool doY = false;
const int maxNumX = 5;
These values will be replaced by the compiler with the given values. Thats the most efficient way. This also of course leads to recompilation as soon as you modify or add values. But in most cases this should not raise practical problems.
Of course there are different solutions:
Using static consts, (or static const class members) the values can be modified without recompilation of all refered files - but thereby the values are held in a const data segment that will be called during runtime rather than being resolved at compile tine. If runtime perfomance is no issue (as it is for 90% of most typical code) thats OK.
The straight C++ way is using class enums rather than global const identifiers (as noted my Mathieu). This is more typesafe and besides this it works much as const: The symbols will be resolved at compile time.

AS3 targeting controller class variable using string

I'm looking for a way of condensing some of my AS3 code to avoid almost duplicate commands.
The issue is that I have multiple variables with almost the same name e.g. frenchLanguage, englishLanguage, germanLanguage, spanishLanguage
My Controller class contains public static variables (these are accessed across multiple classes) and I need a way to be able to call a few of these variables dynamically. If the variables are in the class you are calling them from you can do this to access them dynamically:
this["spanish"+"Language"]
In AS3 it's not possible to write something like:
Controller.this["spanish"+"Language"]
Is there any way to achieve this? Although everything is working I want to be able to keep my code as minimal as possible.
It is possible to access public static properties of a class this way (assuming the class name is Controller as in your example:
Controller['propertyName']
I'm not sure how this helps to have "minimal code", but this would be a different topic/question, which might need some more details on what you want to achive.
Having said that, I like the approach DodgerThud suggests in the comments of grouping similar values in a (dynamic) Object or Dictonary and give it a proper name.
Keep in mind, that if the string you pass in as the key to the class or dynamic object is created from (textual) user input you should have some checks for the validity of that data, otherwise your programm might crash or expose other fields to the user.
It would make sense to utilize a Dictionary object for a set of variables inherited: it provides a solid logic and it happens to work...
I do not think this is what you are trying to accomplish. I may be wrong.
Classes in AS3 are always wrapped within a package - this is true whether you have compiled from Flash, Flex, Air, or any other...
Don't let Adobe confuse you. This was only done in AS3 to use Java-Based conventions. Regardless, a loosely typed language is often misunderstood, unfortunately. So:
this["SuperObject"]["SubObject"]["ObjectsMethod"][ObjectsMethodsVariable"](args..);
... is technically reliable because the compiler avoids dot notation but at runtime it will collect a lot of unnecessary data to maintain those types of calls.
If efficiency becomes an issue..
Use:
package packages {
import flash.*.*:
class This implements ISpecialInterface {
// Data Objects and Function Model
// for This Class
}
package packages {
import...
class ISpecialInterface extends IEventDispatcher

What is the point declaring variables at the end of class?

I saw multiple examples in MSDN that uses to declare the internal fields at the end of the class. What is the point?
I find this a little embarrassing, because each time Visual Studio adds a method it adds it to the end of the class, so there is need every time to move it...
class A
{
public A(){}
// Methods, Properties, etc ...
private string name;
}
class A
{
private string name;
public A(){}
// Methods, Properties, etc ...
}
In C++, it makes sense to put the public interface of the class at the top, so that any user of the class can open up your header file and quickly see what's available. By implication, protected and private members are put at the bottom.
In C# and Java, where interface and implementation are completely intertwined, people would probably not open your class's source code to see what's available. Instead they would rely on code completion or generated documentation. In that case, the ordering of the class members is irrelevant.
If it's obvious the variable has been declared, and the code is by way of an example, then arguably this gets you to the bit being demonstrated quicker - that's all I can think of.
Add-ins like ReSharper will allow you to standardise and automatically apply this layout at the touch of a key combination, by the way, if it is what you want.
Many programmers strive for self-documenting code that helps clients to understand it. In C++ class declaration, they would go from most important (i.e. what is probably most frequently inspected) to least important:
class Class {
public:
// First what interest all clients.
static Class FromFoobar(float foobar); // Named constructors in client code
// often document best
Class(); // "Unnamed" constructors.
/* public methods */
protected:
// This is only of interest to those who specialize
// your class.
private:
// Of interest to your class.
};
Building on that, if you use Qt, the following ordering might be interesting:
class SomeQtClass : public QObject {
public:
signals: // what clients can couple on
public slots: // what clients can couple to
protected:
protected slots:
};
Then the same down for protected and private slots. There is no specific reason why I prefer signals over slots; maybe because signals are always public, but I guess the ordering of them would depend on the situation, anyhow, I keep it consistent.
Another bit I like is to use the access-specifiers to visually seperate behaviour from data (following the importance ordering, behaviour first, data last, because behaviour is the top-interest for the class implementor):
class Class {
private:
void foobar() ;
private:
float frob_;
int glob_;
};
Keeping the last rule helps to prevent visual scattering of class components (we all know how some legacy classes look like over time, when variables and functions are mixed up, not?).
I don't think there is any valid reason for this. If you run Code Analysis on a class declared like this you'll get an error as private fields should be declared on top of classes (and below constants).

How many constructors should a class have?

I'm currently modifying a class that has 9 different constructors. Now overall I believe this class is very poorly designed... so I'm wondering if it is poor design for a class to have so many constructors.
A problem has arisen because I recently added two constructors to this class in an attempt to refactor and redesign a class (SomeManager in the code below) so that it is unit testable and doesn't rely on every one of its methods being static. However, because the other constructors were conveniently hidden out of view about a hundred lines below the start of the class I didn't spot them when I added my constructors.
What is happening now is that code that calls these other constructors depends on the SomeManager class to already be instantiated because it used to be static....the result is a null reference exception.
So my question is how do I fix this issue? By trying to reduce the number of constructors? By making all the existing constructors take an ISomeManager parameter?
Surely a class doesn't need 9 constructors! ...oh and to top it off there are 6000 lines of code in this file!
Here's a censored representation of the constructors I'm talking about above:
public MyManager()
: this(new SomeManager()){} //this one I added
public MyManager(ISomeManager someManager) //this one I added
{
this.someManager = someManager;
}
public MyManager(int id)
: this(GetSomeClass(id)) {}
public MyManager(SomeClass someClass)
: this(someClass, DateTime.Now){}
public MyManager(SomeClass someClass, DateTime someDate)
{
if (someClass != null)
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(SomeOtherClass someOtherClass)
: this(someOtherClass, DateTime.Now){}
public MyManager(SomeOtherClass someOtherClass, DateTime someDate)
{
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(YetAnotherClass yetAnotherClass)
: this(yetAnotherClass, DateTime.Now){}
public MyManager(YetAnotherClass yetAnotherClass, DateTime someDate)
{
myHelper = new MyHelper(yetAnotherClass, someDate, "some param");
}
Update:
Thanks everyone for your responses...they have been excellent!
Just thought I'd give an update on what I've ended up doing.
In order to address the null reference exception issue I've modified the additional constructors to take an ISomeManager.
At the moment my hands are tied when it comes to being allowed to refactor this particular class so I'll be flagging it as one on my todo list of classes to redesign when I have some spare time. At the moment I'm just glad I've been able to refactor the SomeManager class...it was just as huge and horrible as this MyManager class.
When I get around to redesigning MyManager I'll be looking for a way to extract the functionality into two or three different classes...or however many it takes to ensure SRP is followed.
Ultimately, I haven't come to the conclusion that there is a maximum number of constructors for any given class but I believe that in this particular instance I can create two or three classes each with two or three constructors each..
A class should do one thing and one thing only. If it has so many constructors it seems to be a tell tale sign that it's doing too many things.
Using multiple constructors to force the correct creation of instances of the object in a variety of circumstances but 9 seems like a lot. I would suspect there is an interface in there and a couple of implementations of the interface that could be dragged out. Each of those would likely have from one to a few constructors each relevant to their specialism.
As little as possible,
As many as necessary.
9 constructors and 6000 lines in class is a sign of code smell. You should re-factor that class.
If the class is having lot of responsibilities and then you should separate them out. If the responsibilities are similar but little deviation then you should look to implement inheritance buy creating a interface and different implementations.
If you arbitrarily limit the number of constructors in a class, you could end up with a constructor that has a massive number of arguments. I would take a class with 100 constructors over a constructor with 100 arguments everyday. When you have a lot of constructors, you can choose to ignore most of them, but you can't ignore method arguments.
Think of the set of constructors in a class as a mathematical function mapping M sets (where each set is a single constructor's argument list) to N instances of the given class. Now say, class Bar can take a Foo in one of its constructors, and class Foo takes a Baz as a constructor argument as we show here:
Foo --> Bar
Baz --> Foo
We have the option of adding another constructor to Bar such that:
Foo --> Bar
Baz --> Bar
Baz --> Foo
This can be convenient for users of the Bar class, but since we already have a path from Baz to Bar (through Foo), we don't need that additional constructor. Hence, this is where the judgement call resides.
But if we suddenly add a new class called Qux and we find ourselves in need to create an instance of Bar from it: we have to add a constructor somewhere. So it could either be:
Foo --> Bar
Baz --> Bar
Qux --> Bar
Baz --> Foo
OR:
Foo --> Bar
Baz --> Bar
Baz --> Foo
Qux --> Foo
The later would have a more even distribution of constructors between the classes but whether it is a better solution depends largely on the way in which they are going to be used.
The answer: 1 (with regards to injectables).
Here's a brilliant article on the topic: Dependency Injection anti-pattern: multiple constructors
Summarized, your class's constructor should be for injecting dependencies and your class should be open about its dependencies. A dependency is something your class needs. Not something it wants, or something it would like, but can do without. It's something it needs.
So having optional constructor parameters, or overloaded constructors, makes no sense to me. Your sole public constructor should define your class's set of dependencies. It's the contract your class is offering, that says "If you give me an IDigitalCamera, an ISomethingWorthPhotographing and an IBananaForScale, I'll give you the best damn IPhotographWithScale you can imagine. But if you skimp on any of those things, you're on your own".
Here's an article, by Mark Seemann, that goes into some of the finer reasons for having a canonical constructor: State Your Dependency Intent
It's not just this class you have to worry about re-factoring. It's all the other classes as well. And this is probably just one thread in the tangled skein that is your code base.
You have my sympathy... I'm in the same boat.
Boss wants everything unit tested, doesn't want to rewrite code so we can unit test. End up doing some ugly hacks to make it work.
You're going to have to re-write everything that is using the static class to no longer use it, and probably pass it around a lot more... or you can wrap it in a static proxy that accessses a singleton. That way you an at least mock the singleton out, and test that way.
Your problem isn't the number of constructors. Having 9 constructors is more than usual, but I don't think it is necessarily wrong. It's certainly not the source of your problem. The real problem is that the initial design was all static methods. This is really a special case of the classes being too tightly coupled. The now-failing classes are bound to the idea that the functions are static. There isn't much you can do about that from the class in question. If you want to make this class non-static, you'll have to undo all that coupling that was written into the code by others. Modify the class to be non-static and then update all of the callers to instantiate a class first (or get one from a singleton). One way to find all of the callers is to make the functions private and let the compiler tell you.
At 6000 lines, the class is not very cohesive. It's probably trying to do too much. In a perfect world you would refactor the class (and those calling it) into several smaller classes.
Enough to do its task, but remember the Single Responsibility Principle, which states that a class should only have a single responsibility. With that in mind there are probably very few cases where it makes sense to have 9 constructors.
I limit my class to only have one real constructor. I define the real constructor as the one that has a body. I then have other constructors that just delegate to the real one depending on their parameters. Basically, I'm chaining my constructors.
Looking at your class, there are four constructors that has a body:
public MyManager(ISomeManager someManager) //this one I added
{
this.someManager = someManager;
}
public MyManager(SomeClass someClass, DateTime someDate)
{
if (someClass != null)
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(SomeOtherClass someOtherClass, DateTime someDate)
{
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(YetAnotherClass yetAnotherClass, DateTime someDate)
{
myHelper = new MyHelper(yetAnotherClass, someDate, "some param");
}
The first one is the one that you've added. The second one is similar to the last two but there is a conditional. The last two constructors are very similar, except for the type of parameter.
I would try to find a way to create just one real constructor, making either the 3rd constructor delegate to the 4th or the other way around. I'm not really sure if the first constructor can even fit in as it is doing something quite different than the old constructors.
If you are interested in this approach, try to find a copy of the Refactoring to Patterns book and then go to the Chain Constructors page.
Surely a class should have as many constructors as are required by the class... this doesnt mean than bad design can take over.
Class design should be that a constructor creates a valid object after is has finished. If you can do that with 1 param or 10 params then so be it!
It seems to me that this class is used to do way, way to much. I think you really should refactor the class and split it into several more specialized classes. Then you can get rid of all these constructors and have a cleaner, more flexible, more maintainable and more readable code.
This was not at direct answer to your question, but i do believe that if it is necessary for a class to have more than 3-4 constructors its a sign that it probably should be refactored into several classes.
Regards.
The only "legit" case I can see from you code is if half of them are using an obsolete type that you are working to remove from the code. When I work like this I frequently have double sets of constructors, where half of them are marked #Deprecated or #Obsolete. But your code seems to be way beyond that stage....
I generally have one, which may have some default parameters. The constructor will only do the minimum setup of the object so it's valid by the time it's been created. If I need more, I'll create static factory methods. Kind of like this:
class Example {
public:
static FromName(String newname) {
Example* result = new Example();
result.name_ = newname;
return result;
}
static NewStarter() { return new Example(); }
private:
Example();
}
Okay that's not actually a very good example, I'll see if I can think of a better one and edit it in.
The awnser is: NONE
Look at the Language Dylan. Its has a other System.
Instat of a constructors you add more values to your slots (members) then in other language. You can add a "init-keyword". Then if you make a instance you can set the slot to the value you want.
Ofcourse you can set 'required-init-keyword:' and there are more options you can use.
It works and it is easy. I dont miss the old system. Writing constructors (and destructors).
(btw. its still a very fast language)
I think that a class that has more than one constructor has more than one responsibility. Would be nice to be convinced about the opposite however.
A constructor should have only those arguments which are mandatory for creating the instance of that class. All other instance variables should have corresponding getter and setter methods. This will make your code flexible if you plan to add new instance variables in the future.
In fact following OO principle of -
For each class design aim for low coupling and high cohesion
Classes should be open for extension but closed for modification.
you should have a design like -
import static org.apache.commons.lang3.Validate.*;
public class Employee
{
private String name;
private Employee() {}
public String getName()
{
return name;
}
public static class EmployeeBuilder
{
private final Employee employee;
public EmployeeBuilder()
{
employee = new Employee();
}
public EmployeeBuilder setName(String name)
{
employee.name = name;
return this;
}
public Employee build()
{
validateFields();
return employee;
}
private void validateFields()
{
notNull(employee.name, "Employee Name cannot be Empty");
}
}
}