Related
I have an object, let's call it a Request, that has associations to several other objects like:
Employee submitter;
Employee subjectsManager;
Employee pointOfContact;
And several value properties like strings, dates, and enums.
Now, I also need to keep track of another object, the subject, but this can be one of 3 different types of people. For simplicity let's just talk about 2 types: Employee and Consultant. Their data comes from different repositories and they have different sets of fields, some overlapping. So say an employee has a
String employeeName;
String employeeId;
String socialSecurityNumber;
Whereas a consultant has
String consultantName;
String socialSecurityNumber;
String phoneNumber;
One terrible idea is that the Request has both a Consultant and an Employee, and setSubject(Consultant) assigns one, setSubject(Employee) assigns the other. This sounds awful. One of my primary goals is to avoid "if the subject is this type then do this..." logic.
My thought is that perhaps an EmployeeRequest and a ConsultantRequest should extend Request, but I'm not sure how, say, setSubject would work. I would want it to be an abstract method in the base class but I don't know what the signature would be since I don't know what type the parameter would be.
So then it makes sense to go at it from an interface perspective. One important interface is that these Request objects will be passed to a single webservice that I don't own. I will have to map the object's fields in a somewhat complex manner that partially makes sense. For fields like name and SSN the mapping is straightforward, but many of the fields that don't line up across all types of people are dumped into a concatenated string AdditionalInfo field (wump wump). So they'll all have a getAdditionalInfo method, a getName, etc, and if there's any fields that don't line up they can do something special with that one.
So that makes me feel like the Request itself should not necessarily be subclassed but could contain a reference to an ISubjectable (or whatever) that implements the interface needed to get the values to send across the webservice. This sounds pretty decent and prevents a lot of "if the subject is an employee then do this..."
However, I would still at times need to access the additional fields that only a certain type of subject has, for example on a display or edit page, so that brings me right back to "if subject is instance of an employee then go to the edit employee page..." This may be unavoidable though and if so I'm ok with that.
Just for completeness I'll mention the "union of all possible fields" approach -- don't think I'd care to do that one either.
Is the interface approach the most sensible or am I going about it wrong? Thanks.
A generic solution comes to mind; that is, if the language you're using supports it:
class Request<T extends Subject> {
private T subject;
public void setSubject(T subject) {
this.subject = subject;
}
public T getSubject() {
return subject;
}
}
class EmployeeRequest extends Request<Employee> {
// ...
}
class ConsultantRequest extends Request<Consultant> {
// ...
}
You could similarly make the setSubject method abstract as you've described in your post, and then have separate implementations of it in your subclasses. Or you may not even need to subclass the Request class:
Request<Employee> employeeRequest = new Request<>();
employeeRequest.setSubject(/* ... */);
// ...
int employeeId = employeeRequest.getSubject().getEmployeeId();
I'm relatively new to this site so if I am doing something wrong when it comes to posting questions and whatnot please let me know so I can fix it for next time.
I'm curious as to whether or not it is bad OOP practice to subclass multiple classes from a single base class. That probably doesn't quite make sense so I'm going to elaborate a little bit.
Say for instance you are designing a game and you have several different monsters you might come across. The approach I would take is to have a base abstract class for just a general monster object and then subclass all of the specific types of monsters from the base class using a new class.
One of my instructors told me that you shouldn't rely on inheritance in this case because the number of monsters will continue to grow and grow and the number of classes will increase to a point where it is hard to keep track of all of them and thus yo will have to recompile the program with every new class added in the future.
I don't understand why (or even if) that's a bad thing. If anybody could help me understand where my professor is coming from that would be much appreciated.
Thanks!
If monsters are very similar, in that the only differences are (for example) their name, how much damage they impart, what color they are, etc., then these differences which can be reflected in a field (in values), may make sub-classing unnecessary.
If, however, you have monsters that are fundamentally different from others, such that it is necessary to have very different methods and logic, and more specifically, differences that cannot be reflected in fields, then a sub-class SpecialMonster may be necessary.
But again, even SpecialMonster may not need to be sub-classed by individual monster types, as it's fields may be enough to distinguish between them.
While it's legal to have a million sub-classes of specific monster types, you don't want to take care of all that duplicate code when it could simply be expressed in the fields of new Monster instances, such as
new Monster("Goob", WakeTime.NOCTURNAL, 35, new Weapon[]{sword, hammer, knittingNeedle});
new Monster("Mister Mxyzptlk", WakeTime.ANYTIME, 71, new Weapon[]{sword, mindMeld, cardboardCutter});
There is an alternative, where you do have a lot of classes, but you don't impose them onto your users, and you don't clutter up your API/JavaDoc with them. If your Monster happens to be an abstract class
public abstract class Monster {
private final String name;
...
public Monster(String name, int default_damage, WakeTime wake_time, Weapon[] weapons) {
this.name = name;
...
}
public String getName() {
return name;
}
...
public abstract int getDamage(int hit_strength);
}
Then you could have a Monster convenience creator like this:
/**
<P>Convenience functions for creating new monsters of a specific type.</P>
**/
public class NewMonsterOfType {
private NewMonsterOfType() {
throw new IllegalStateException("Do not instantiate.");
}
/**
<P>Creates a new monster that is nocturnal, has 35-default-damage, and whose weapens are: sword, hammer, knittingNeedle.</P>
**/
public static final GOOB = new GoobMonster();
/**
<P>Creates a new monster that can be awake at any time, has 71-default-damage, and whose weapens are: sword, mindMeld, cardboardCutter.</P>
**/
public static final MISTER_MXYZPTLK = new MisterMxyzptlkMonster();
}
class GoobMonster extends Monster {
public GoobMonster() {
super("Goob", WakeTime.NOCTURNAL, 35, new Weapon[]{sword, hammer, knittingNeedle});
}
public int getDamage(int hit_strength) {
return (hit_strength < 70) ? getDefaultDamage() : (getDefaultDamage() * 2);
}
}
class MisterMxyzptlkMonster extends Monster {
public GoobMonster() {
super("Mister Mxyzptlk", WakeTime.ANYTIME, 71, new Weapon[]{sword, mindMeld, cardboardCutter});
}
public int getDamage(int hit_strength) {
return (hit_strength < 160) ? getDefaultDamage() + 10 : (getDefaultDamage() * 3);
}
}
In order for these private (actually package-protected) classes to not show up in you JavaDoc, you need to set its access to something either protected or public.
Inheritance is quite natural in your scenario as all the specific monsters ARE base monsters as well :). I'd actually use inheritance a lot here, since probably specific monsters do have specific behaviour that would have to be overriden. MonsterA might move by crawling while MonsterB might move by flying. The base AMonster would have an abstract Move() method , implemented by those sub types.
This isn't a final answer, it really much depends on the game needs, however, in simplified form, inheritance makes sense here. The number of monster types might continue to grow, but really, are they all the same? The monster design is just based on grouping together some predefined data/behaviour? The game is quite trivial then...
I really get the impression your instructor doesn't code games for a living (me neither, although I did make a game some time ago), but his explanation why you shouldn't use inheritance is way too simplified. The number of defined classes is never an issue in an app, the more the better IF the Single Responsibility Principle is respected.
About you have to recompile your app.... yeah, when you fix a bug you have to recompile it too. IMO, the reasons he gave to you aren't valid for this scenario. He needs to come up with much better arguments.
In the mean time, go for inheritance.
Theoretical question needs theoretical answer :).
It is not just bad, it is pointless. You should have a LIMITED number of "base" classes that inherits from other classes, and those classes should be composed from other classes (vide favour composition versus inheritance).
So as complexity grows the number of classes that base classes are composed from should grows. Not number of base classes itself.
It is like in the industry. If you see machines for instance, they are really composed from large quantity of small parts, and some of those small parts are the same in different machines. When yo designing new machine you do not order new unique "base" part for it just to have a name for your new machine. You use parts existing on a market and you designing some new parts (not "base") only if you cannot find existing counterparts...
I have read in many places that "getters and setters are evil". And I understood why so. But I don't know how to avoid them completely. Say Item is a class that has information about item name, qty, price etc...
and ItemList is a class, which has a list of Items. To find the grand total:
int grandTotal()
{
int total = 0;
for (Item item: itemList)
total += item.getPrice();
return total;
}
In the above case, how does one avoid getPrice()? The Item class provides getName, setName, etc....
How do I avoid them?
When should you use getters and setters?
Getters and setters are great for configuring or determining the configuration of a class, or retrieving data from a model
Getting the price of an item is an entirely reasonable use of a getter. That is data that needs to be available and may involve special considerations to protect the data by adding validation or sanitization to the setter.
You can also provide getters without setters. They do not have to come in pairs.
When shouldn't you use getters and setters?
Sometimes objects rely on internal properties that will never be exposed. For example, Iterators and internal collections. Exposing the internal collection could have dramatically negative and unexpected consequences.
Also, for example, let's say you are communicating via some HttpURLConnection. Exposing the setter for your HttpURLConnection means that you could end up with a very odd state should the connection be changed while waiting to receive data. This connection is something that should be created on instantiation or entirely managed internally.
Summary
If you have data that is for all intents and purposes public, but needs to be managed: use getters and setters.
If you have data that needs to be retrieved but under no circumstances should ever be changed: use a getter but not a setter.
If you have data that needs to be set for internal purposes and should never be publicly exposed (and cannot be set at instantiation): use a setter but not a getter (setter presumably prevents a second call affecting the internal property)
If you have something that is entirely internal and no other class needs to access it or change it directly, then use neither.
Don't forget that setters and getters can be private and even for internally managed properties, having a setter that manages the property may be desirable. For example, taking a connection string and passing it to the setter for HttpURLConnection.
Also note:
Allen Holub's article Why getter and setter methods are evil seems to be the source of OP's reasoning but, in my opinion, the article does a poor job of explaining its point.
Edit: Added summary
Edit 2: spelling corrections
It's a shame to see a small, vocal minority take a back lash against the whole "Getters and Setters" are evil debate. Firstly the article title is purposely provocative to draw you in, as should any blog post. I've in turn blogged about this before and several years later updated my opinions and ideas about this question. I'll summarise the best I can here.
Getters and setters (accessors) are not evil
They are "evil" (unnecessary) most of the time however
Encapsulation is not just adding accessors around private fields to control change, after all there is no benefit to added get/set methods that just modify a private field
You should write as much code as possible with the principle of "Tell, Don't Ask"
You need to use accessors for framework code, DTOs, serialisation and so forth. Don't try to fight this.
You want your core domain logic (business objects) to be as property free as possible however. You should tell objects to do stuff, not check their internal state at will.
If you have a load of accessors you essentially violate encapsulation. For example:
class Employee
{
public decimal Salary { get; set; }
// Methods with behaviour...
}
This is a crap domain object, because I can do this:
me.Salary = 100000000.00;
This may be a simple example, but as anyone who works in a professional environment can attest to, if there is some code that is public people will make use of it. It would not be wrong for a developer to see this and start adding loads of checks around the codebase using the Salary to decide what do with the Employee.
A better object would be:
class Employee
{
private decimal salary;
public void GivePayRise()
{
// Should this employee get a pay rise.
// Apply business logic - get value etc...
// Give raise
}
// More methods with behaviour
}
Now we cannot rely on Salary being public knowledge. Anyone wanting to give a pay rise to employees must do this via this method. This is great because the business logic for this is contained in one place. We can change this one place and effect everywhere the Employee is used.
The following sample is a brilliant example of boilerplate setters and getters.
class Item{
private double price;
public void setPrice(final double price){
this.price = price;
}
public double getPrice(){
return this.price;
}
}
Some coders think that this is called encapsulation, but in fact this code is exact equivalent of
class Item{
public double price;
}
In both classes price is not protected or encapsulated, but the second class reads easier.
class Item{
private double price;
public void setPrice(final double price){
if(isValidPrice(price))
this.price = price;
else throw new IllegalArgumentException(price+" is not valid!");
}
public double getPrice(){
return this.price;
}
}
This is a real encapsulation, the invariant of the class is guarded by the setPrice. My advice - don't write dummy getters and setters, use getters and setters only if they guard the invariant of your class
I have read in many places that "getters and setters are evil".
Really? That sounds crazy to me. Many? Show us one. We'll tear it to shreds.
And I understood why so.
I don't. It seems crazy to me. Either your misunderstood but think you did understand, or the original source is just crazy.
But I don't know how to avoid them completely.
You shouldn't.
how to avoid getPrice?
See, why would you want to avoid that? How else are you suppose to get data out of your objects?
how to avoid them???
Don't. Stop reading crazy talk.
When someone tells you that getters and setters are evil, think about why they are saying that.
Getters
Are they evil? There is no such thing as evil in code. Code is code and is neither good nor bad. It's just a matter of how hard it is to read and debug.
In your case, I think it is perfectly fine to use a getter to calculate the final price.
The "evil"
Usecase: you think you want the price of an item when buying something.
People sometimes use getters like this:
if(item.getPrice() <= my_balance) {
myBank.buyItem(item);
}
There is nothing wrong with this code, but it isn't as straight-forward as it could be. Look at this (more pragmatic approach):
myBank.buyItem(item); //throws NotEnoughBalanceException
It's not the buyers or the cashiers job to check the price of an item when buying something. It's the actually the bank's job. Imagine that customer A has a SimpleBank.java
public class SimpleBank implements Transaction {
public void buyItem(Item item){
if(getCustomer().getBalance() >= item.getPrice()){
transactionId = doTransaction(item.getPrice());
sendTransactionOK(transactionId);
}
}
}
The first approach seems fine here. But what if customer B has a NewAndImprovedBank.java?
public class NewAndImprovedBank implements Transaction {
public void buyItem(Item item){
int difference = getCustomer().getBalance() - item.getPrice();
if (difference >= 0) {
transactionId = doTransaction(item.getPrice());
sendTransactionOK(transactionId);
} else if (difference <= getCustomer().getCreditLimit()){
transactionId = doTransactionWithCredit(item.getPrice());
sendTransactionOK(transactionId);
}
}
}
You might think that you are being defensive when using the first approach, but actually you are limiting the capabilities of your system.
Conclusion
Don't ask for permission aka item.getPrice() , ask for forgiveness aka NotEnoughBalanceException instead.
getPrice() is accessing a private variable I'm assuming.
To answer your question directly, make the price variable public, and code something like (syntax may differ depending on language, use of pointers etc):
total += item.price;
However this is generally considered bad style. Class variables should generally remain private.
Please see my comment on the question.
How to avoid getters and setters? Design classes that actually act upon the data they hold.
Getters lie about the data anyway. In the Item.getPrice() example, I can see I'm getting an int. But is the price in dollars or cents? Does it include tax(es)? What if I want to know the price in a different country or state, can I still use getPrice()?
Yes, this might be beyond the scope of what the system is designed to do, and yes, you might just end up returning a variable's value from your method, but advertising that implementation detail by using a getter weakens your API.
'Evil' as .getAttention()
This has been discussed often, and even perhaps went a bit viral, as a result of the pejorative term "Evil" used in the dialog. There are times when you need them, of course. But the problem is using them correctly. You see, Professor Holub's rant isn't about what your code is doing now, but about boxing yourself in so that change in the future is painful and error prone.
In fact, all I have read by him carries this as its theme.
How does that theme apply to the class Item?
A look at the future of Item
Here is fictions's item class:
class Item{
private double price;
public void setPrice(final double price){
if(isValidPrice(price))
this.price = price;
else throw new IllegalArgumentException(price+" is not valid!");
}
public double getPrice(){
return this.price;
}
}
This is all well and good- but it is still 'Evil' in the sense that it could cause you a lot of grief in the future.
The grief is apt to come from the fact that one day 'price' may have to take different currencies into account (and perhaps even more complex barter schemes). By setting price to be a double, any code that is written between now and the 'apocalypse' (we're talking evil, after all) will be wiring price to a double.
It is much better (even Good, perhaps) to pass in a Price object instead of a double. By doing so you can easily implement changes to what you mean by 'price' without breaking the existing interfaces.
The takeaway on getters and setters
If you find yourself using getters and setters on simple types, make sure you consider possible future changes to the interface. There is a very good chance you shouldn't be. Are you using setName(String name)? You should consider setName(IdentityObject id) or even setIdentity(IdentityObject id) in case other identification models show up (avatars, keys, whatever). Sure you can always go around and setAvatar and setKey on everything, but by using an object in your method signature you make it easier to extend in the future to the objects that can use the new identity properties and not break the legacy objects.
A different perspective that is missing here so far: getters and setters invite to violate the Tell Don't Ask principle!
Imagine you go shopping in the supermarket. In the end, the cashier wants money from you. The getter/setter approach is: you hand over your purse to the cashier, the cashier counts the money in your purse, takes the money you owe, and gives back the purse.
Is that how you do things in reality? Not at all. In the real world, you typically don't care about the internal state of "autonomous" other "objects". The cashier tells you: "your bill is 5,85 USD". Then you pay. How you do that is up to you, the only thing the cashier wants/needs is he receives that amount of money from your side.
Thus: you avoid getters and setters by thinking in terms of behavior, not in terms of state. Getters/setters manipulate state, from the "outside" (by doing avail = purse.getAvailableMoney() and purse.setAvailableMoney(avail - 5.85). Instead, you want to call person.makePayment(5.85).
How to avoid getters and setters in Java?
Use Project Lombok
Cloudanger answer is is one, but you must also realize that the item list will likely contain many item objects with quantity ordered on it.
Solution : create another class in between them that stores your item in the item list and the qty ordered for that item (Let's say the class is called OrderLine).
OrderLine will have Item and qty as fields.
After that, code something like calculateTotal(int qty) in Item which return price*qty.
Create a method in OrderLine that call calculateTotal(qtyOrdered)
Pass the return value to the itemList.
This way, you avoid getters.
The ItemList will only know the total price.
Your code should live with your data.
Ask the Object who has the data to calculate the totalPrice instead of asking that object for raw data to calculate your totalPrice.
Really?
I don't think that. on the contrary the getters and setters help you to protect the consistense of the variables.
The importance of getters and setters is to provide protection to private attributes so that they can not be accessed directly for this it is best that you create a class with the attribute item in which you include the corresponding get and set.
Use a helper class ShoppingCart. Item's method item.addTo(ShoppingCart cart) would add the price to the totalSum of the cart using shoppingCart.addItem(Item item, int price)
Dependency from Item to ShoppingCart isn't disadvantageous if the Items are meant to be items of ShoppingCarts.
In the case where Items live solely for the ShoppingCart and the Item class is small, I would more likely have the Item as an inner class of the ShoppingCart, so that the ShoppingCart would have access to the private variables of the items.
Other thoughts
It would also be possible, although quite unintuitive design, to have the Item class count the sum (item.calculateSum(List<Item> items)), since it can access the private parts of other items without breaking encapsulation.
To others wondering why the getters are bad. Consider the given example where the getPrice() returns integer. If you would want to change that to something better like BigDecimal at least or a custom money type with currency, then it wouldn't be possible since the return type int exposes the internal type.
Getters and setters are evil because they break encapsulation and can unnecessarily expose an objects internal state and allow it to be modified in way it should not be. The following article elaborates on this problem:
http://programmer.97things.oreilly.com/wiki/index.php/Encapsulate_Behavior,_not_Just_State
You can avoid getter and setter at places by using _classname__attributename because that's the changed new name once you declare private to any attribute.
So if Item is the class with a private attribute declared as __price
then instead of item.getPrice() you can write _Item__price.
It will work fine.
My brother-in-law is a freshman engineering major in college. He has no prior programming experience. He is learning programming in his classes, but he seems to be struggling with the basic concepts. It doesn't help that he seems to be the only person in all his classes without some background in programming.
He did OK in Matlab (which I don't know), and then I helped him along when he was learning the basics of Python. Pretty soon his courses will start on C and C++. I'm worried that he will be left behind when Object-Oriented Programming comes up.
I tried explaining it to him with the analogy of a car.
Pseudocode:
Class Car
{
public string make;
public string model;
private string milesPerGallon;
private float gasolineGallonsInTank = 0;
private float tankCapacity;
private float odometer = 0;
public Car(maxGas, mpg)
{
tankCapacity = maxGas;
milesPerGallon = mpg;
}
public void fillTank()
{
gasolineGallonsInTank = tankCapacity;
}
public void drive(float miles)
{
if (miles == 0)
{
print("You don't want to drive?");
return;
}
if(miles < 0)
{
print("Ok, we're driving in reverse!");
miles = Math.AbsoluteValue(miles);
}
float maxDistance = gasolineGallonsInTank / milesPerGallon;
if (maxDistance >= miles)
{
odometer += maxDistance;
gasolineGallonsInTank = 0;
print("You've run out of gas!");
return;
}
odometer += miles;
gasolineGallonsInTank -= miles / milesPerGallon;
}
public float readOdometer()
{
return odometer;
}
}
I said that the Car class was like a car factory, and var mySedan = new Car(12, 20) was like producing a new car with a 12-gallon gas tank and 20 mpg. Then I showed him how the methods could be run, and it was like things were happening to the car.
Then I made a second car: var myMiniVan = new Car(21.5, 14) and showed how running methods on one car didn't affect the other.
But he didn't get it. All of this went way over his head. Is there a better or simpler visual analogy I can use? Am I explaining it wrong?
Our teacher used:
cars and their components - to explain classes, fields, methods, and to show what is aggregation and composition
animals (man, tiger and cat, exactly :)) - to explain inheritance
shapes - to explain more inheritance and polymorphism
Also, as far as I remember, there were some good examples in OOA&D book by Grady Booch.
On first OOP seminar we did rather unusual an interesting exercise: we implemented "classes" in C (not C++). We had to use structs and pointers to functions - this made us feel, what is state, what is behavior, what are class and objects. Then we proceeded to C++.
UPDATE
I just have remembered one more good and descriptive example of basic OOP concepts: GUI components (Buttons, TextBoxes, Captions, Dialogs). These examples are not as "abstract" as animals and cars, and they are rather descriptive - result can be seen immediately.
There are many GUI frameworks, - you just can suggest your brother to play with one of them.
Does he like beer?
http://keithchadwick.wordpress.com/2010/03/20/the-oo-beer-case-analogy/
Maybe you should take a program he understands (in python for example). And show him the benefits of following a oo approach. This is how i learned C++ after having some basic C knowledge.
But i thought your explanation was pretty clear already.
Another good analogy (especially for an engineering student) might be machine parts.
Take a carburettor. Carburrettor A is designed to meet certain spects for a certain motor, including the INTERFACE (usually sealed with a gasket which also conforms to the interface) between the manifold and carb.
There are certain holes on either surface which must line up just so, and fuel is expected to be delivered from the gas line to the carburettor at a specific pressure and volume rate. The Carb is expected to deliver a certain fuel-air mixture to the manifold for a certain vacuum pressure, etc.
This is a good starting perspective for the public interface. Carb Manufacturers dont need to know much about the motor other than the template for the interface between their carb and the manifold, and certain specs for fuel-air mixture and volume expected at the manifold. Likewise, the motor doesn't care HOW the carb does what it does, it simply needs to deliver fuel, at the proper pressure, to the proper hole in the manifold, so that the carb can perform some magic function, and deliver the proper fuel air mixture on demand. Different manufacturers may achieve this in different ways, but as long as the inputs and outputs are the same, everything works fine.
INSIDE the carb, there is all manner of stuff happening to better control the flow of fuel, and measure the vacuum pressure with pitot tubes, and such. These are akin to PRIVATE functions and methods. The means by which the carburettor knwos that, given Vacuum pressure of X, I need to supply qty of Fuel Y and air volume Z to the manifold.
While this does not necessarily do as good a job of describing Private member variables, getters vs setters, and the like, it MAY help with the concept to Interface, excapsulation, and Private vs Public methods. For me, this was initially harder to graps than private member variables and such (especially the "Interface" part . . .).
Programming is best learned by doing.
Work with him on writing a simple address book application. (No need to save anything, as this is a OOP learning experience.) Make a class CEntry that would represent each record in the address book. It would contain things such as the person's name, street address, city, state, zip code, and phone number. The make another class CName, which would have members first, middle, and last. Finally, make a third class CPhone which would have members for country, area_code, prefix, and number. As he writes it, you can explain why the use of classes makes sense for this application, as well as the benefits and drawbacks of having CEntry inherit from CName and CPhone or contain new instances of those classes.
I'm often running into the same trail of thought when I'm creating private methods, which application is to modify (usually initialize) an existing variable in scope of the class.
I can't decide which of the following two methods I prefer.
Lets say we have a class Test with a field variable x. Let it be an integer. How do you usually modify / initialize x ?
a) Modifying the field directly
private void initX(){
// Do something to determine x. Here its very simple.
x = 60;
}
b) Using a return value
private int initX(){
// Do something to determine x. Here its very simple.
return 60;
}
And in the constructor:
public Test(){
// a)
initX();
// b)
x = initX();
}
I like that its clear in b) which variable we are dealing with. But on the other hand, a) seems sufficient most of the time - the function name implies perfectly well what we are doing!
Which one do you prefer and why?
Thank for your answers guys! I'll make this a community wiki as I realize that there is no correct answer to this.
I usually prefer b), only I pick a different name, like computeX() in this case. A few reasons for why:
if I declare computeX() as protected, there is a simple way for a subclass to influent how it works, yet x itself can remain a private field;
I like to declare fields final if that's what they are; in this case a) is not an option since initialization has to happen in compiler (this is Java-specific, but your examples all look Java as well).
That said, I don't have a strong preference between the two methods. For instance, if I need to initialize several related fields at once, I will usually pick option a). That, though, only if I cannot or don't want for some reason, to initialize directly in constructor.
For initialization I prefer constructor initialization if it's possible,
public Test():x(val){...}, or write initialization code in the constructor body. Constructor is the best place to initialize all the fields (actually, it is the purpose of constructor). I'd use private initX() approach only if initialization code for X is too long (just for readability) and call this function from constructor. private int initX() in my opinion has nothing to do with initialization(unless you implement lazy initialization,but in this case it should return &int or const &int) , it is an accessor.
I would prefer option b), because you can make it a const function in languages that support it.
With option a), there is a temptation for new, lazy or just time-stressed developers to start adding little extra tasks into the initX method, instead of creating a new one.
Also, in b), you can remove initX() from the class definition, so consumers of the object don't even have to know it's there. For example, in C++.
In the header:
class Test {
private: int X;
public: Test();
...
}
In the CPP file:
static int initX() { return 60; }
Test::Test() {
X = initX();
}
Removing the init functions from the header file simplifies the class for the people that have to use it.
Neither?
I prefer to initialize in the constructor and only extract out an initialization method if I need a lot of fields initialized and/or need the ability to re-initialize at another point in the life time of an instance (without going through a destruct/construct).
More importantly, what does 60 mean?
If it is a meaningful value, make it a const with a meaningful name: NUMBER_OF_XXXXX, MINUTES_PER_HOUR, FIVE_DOZEN_APPLES, SPEED_LIMIT, ... regardless of how and where you subsequently use it (constructor, init method or getter function).
Making it a named constant makes the value re-useable in and of itself. And using a const is much more "findable", especially for more ubiquitous values (like 1 or -1) then using the actual value.
Only when you want to tie this const value to a specific class would it make sense to me to create a class const or var, or - it the language does not support those - a getter class function.
Another reason to make it a (virtual) getter function would be if descendant classes need the ability to start with a different initial value.
Edit (in response to comments):
For initializations that involve complex calculations I would also extract out a method to do the calculation. The choice of making that method a procedure that directly modifies the field value (a) or a function that returns the value it should be given (b), would be driven by the question whether or not the calculation would be needed at other times than "just the constructor".
If only needed at initialization in the constructor, I would prefer method (a).
If the calculation needs to be done at other times as well, I would opt for method (b) as it also makes it possible to assign the outcome to some other field or local variable and so can be used by descendants or other users of the class without affecting the inner state of the instance.
Actually only a) method behaves as expected (by analyzing method name). Method b) should be named 'return60' in your example or 'getXValue' in some more complicated one.
Both options are correct in my opinion. It all depeneds what was your intention when certain design was choosen. If your method has to do initialization only I would prefer a) beacuse it is simplier. In case x value is also used for something else somewhere in logic using b) option might lead to more consistent code.
You should also always write method names clearly and make those names corresponding with actual logic. (in this case method b) has confusing name).
#Frederik, if you use option b) and you have a LOT of field variables, the constructor will become a quite unwieldy block of code. Sometimes you just can't help but have lots and lots of member variables in a class (example: it's a domain object and it's data comes straight from a very wide table in the database). The most pragmatic approach would be to modularize the code as you need to.