most recent 30 from softwareengineering.stackexchange.com2025-05-01T21:00:34Zhttps://softwareengineering.stackexchange.com/feeds/tag/programming-practices+object-oriented+javahttps://creativecommons.org/licenses/by-sa/4.0/rdfhttps://softwareengineering.stackexchange.com/q/149563276Slamicehttps://softwareengineering.stackexchange.com/users/405312012-05-22T02:06:38Z2023-11-11T08:19:28Z
<p>I was told by a colleague that in Java object creation is the most expensive operation you could perform. So I can only conclude to create as few objects as possible.</p>
<p>This seems somewhat to defeat the purpose of object oriented programming. If we aren't creating objects then we are just writing one long class C style, for optimization?</p>
https://softwareengineering.stackexchange.com/q/4451432jokerhttps://softwareengineering.stackexchange.com/users/4228742023-04-20T16:51:13Z2023-04-21T19:36:58Z
<p>I have a java class with an <code>init</code> method. It's different from the constructor. The constructor just initializes the variables/fields. The <code>init</code> method connects to a database and performs some verifications on the database + it kick starts a background thread which handles incoming requests.</p>
<p>If you wanna think of it in pseudo-code:</p>
<pre><code>class SomeService:
...
queue
other fields
...
public SomeService(Constructor input):
initializes fields...
public void init():
connect to database and verify certain existence of a table
start a thread
initialized = true
public String doSomething(Some Input):
if !initialized: throw exception
add job to queue to be picked up by the running thread
public Integer doSomethingElse(Some Other Input):
if !initialized: throw exception
add job to queue to be picked up by the running thread
</code></pre>
<p>My question is, is it better to force the object user to call init before using the class methods? If you check the code above, any method will throw exception if it's called before <code>init</code>.</p>
<p><strong>Benefits</strong>:</p>
<ul>
<li>This provides separation of concerns -- a method is only responsible of doing its job.</li>
</ul>
<p><strong>Downside</strong>:</p>
<ul>
<li>This, however, makes a bad class usability: what if init failed? the object user will always has to handle this. And might even try to call <code>init</code> before every other class method call.</li>
</ul>
<p>The other option is call <code>init</code> at the beginning of every class method, internally.</p>
<p><strong>Benefits</strong>:</p>
<ul>
<li>The class user doesn't need to worry about anything but getting his services done by the object.</li>
</ul>
<p><strong>Downside</strong>:</p>
<ul>
<li>Now a method isn't as good in terms of separation of concerns. It does its job after it tries to initialize the object.</li>
</ul>
<p>Please note that the initialization procedure is a must before any other method does its job. Other methods won't be functional unless the object is initialized by calling <code>init</code>.</p>
<p>I believe it's obvious why I separated <code>init</code> from the constructor:</p>
<ol>
<li>It's perfectly fine to have the object without it being initialized, and leave initialization for later.</li>
<li>A constructor shouldn't take long for initialization, which isn't the case. Connection to database, running multiple statements, and starting a thread. This isn't as snappy as just setting fields values.</li>
<li>If connection to database failed in a constructor, this will result in no object creation. This is bad behavior because the database can be available some other time after trial of object instantiation.</li>
</ol>
<p>What I did is:</p>
<ul>
<li>Called <code>init</code> at the beginning of every method. To get the benefit of that.</li>
<li>Availed <code>init</code> as public method to permit object caller for eager initialization.</li>
</ul>
<p>So, what is it do you think is better? Call <code>init</code> at the beginning of every method? Leave it completely for the object user to handle it?</p>
<p>I tried to look it up but didn't find a fruitful answer.</p>
<p>I also tried to find in java 8 standard library if any class has init method, but couldn't find any. However, I found in java extension, <code>Cipher</code> class, which has <code>init</code>. and it works like approach#1 (leave it to the caller). That being said, this makes sense because its <code>init</code> takes user input, while mine doesn't.</p>
<p>I asked a chatgpt based bot and I got an answer that I should go with approach#2, calling <code>init</code> at the beginning of every method.</p>
https://softwareengineering.stackexchange.com/q/2786762john01davhttps://softwareengineering.stackexchange.com/users/1274782015-04-09T18:02:40Z2023-02-12T20:35:27Z
<p>I am currently working on a semi-large project that has several packages. There are 3 main packages, a "client" package, a "server" package and a "common" package. There are two jars, one for the client and one for the server each containing their own package and the common package. As is implied by the package names, there is a server and a client. The clients connect to the server and exchange messages. These messages take the form of a serilized subclass of Message. All subclasses of Message are in the common package. When a message is recieved, a method is called on the message class to handle the message. There is one subclass of Message that is responsible for sending the name of the clients to the servers. In the method that is called when the server recieves it, it then calls a setName() method on the object representing the connection between the server and client. </p>
<p>For obvious reasons, I don't want external programmers calling the setName() method however it has to be public because the message and the class to represent a connection are in different packages. I would like to know if it is good form to deprecate the method with a reason along the lines of "for internal use only", and if not, what is a better option?</p>
https://softwareengineering.stackexchange.com/q/437873-1Wiktorhttps://softwareengineering.stackexchange.com/users/3921202022-04-06T21:14:41Z2022-04-08T12:09:14Z
<p><strong>Background:</strong>
I'm coding an app, the core idea is simple - I can choose a 'Task' (consists of name, code to perform aka Runnable, progress) through GUI, start it, stop it, start all 'Task's and stop all 'Task's. Each 'Task' has to be dispatched on different thread (long operations).</p>
<p><strong>The problem:</strong>
As mentioned, 'Task' class has ability to be started or stopped. Normally, I'd introduce a manager class like 'TaskManager' in order to literally manage tasks (let's say starting them on a different thread and keeping the handle in order to cancel it or keeping an eye on the threads amount - limited resources), but I've heard that Manager type of classes can be <em>smelly</em> and just poor practice.</p>
<p><strong>Core question:</strong>
Do I really need that kind of manager class?</p>
https://softwareengineering.stackexchange.com/q/3665372jarerhttps://softwareengineering.stackexchange.com/users/2970942018-02-25T10:37:59Z2021-02-17T16:34:16Z
<p>What should a constructor contain?</p>
<p>In both cases, all three arguments are needed for the class to work.</p>
<p>Which approach is better and why?</p>
<p>1)</p>
<pre><code>class Language {
LanguageRepository languageRepository;
Language(LanguageRepository languageRepository) {
this.languageRepository = languageRepository;
}
public void doThat(String firstArg, String secondArg) {
languageRepository(firstArg, secondArg);
}
}
</code></pre>
<p>2)</p>
<pre><code>class LanguageDoThat {
Language(LanguageRepository languageRepository, String firstArg, String secondArg) {
languageRepository(firstArg, secondArg)
}
}
</code></pre>
<p>3)</p>
<pre><code>class Language {
LanguageRepository languageRepository;
String firstArg;
String secondArg;
Language(LanguageRepository languageRepository, String firstArg, String secondArg) {
this.languageRepository = languageRepository;
this.firstArg = firstArg;
this.secondArg = secondArg;
}
public void doThat() {
languageRepository(firstArg, secondArg);
}
}
</code></pre>
<p>or other?</p>
<p>There are only examples, but in these classes there will be no more methods.</p>
https://softwareengineering.stackexchange.com/q/3812517Zibbobzhttps://softwareengineering.stackexchange.com/users/1239582018-11-09T16:32:29Z2018-11-09T17:19:50Z
<p>I'm doing code review on a change my co-worker made to our Java application, and I've found something I'm not very familiar with - a nested class. </p>
<p>From reviewing the code, it seems like the nested class is being used as if it were a normal class - and asking my co-worker about it, the reason for putting it in as a nested class is because of a source control issue preventing her from creating a new class on the day she coded it. </p>
<p>Now this is bothering me - because while there's no reason to introduce this element into our code (very few classes use nested classes in our application), there's also no drawbacks to it that I can think of either. The nested class is, in a very loose way, related to the class it came from, and re-writing the code so that the nested class is an independent one would take some time. </p>
<p>Is there any good reason to have my co-worker redo the code so that this nested class is independent? Or would I just be asking them to waste their time on something that does not matter? </p>
<p>Note that there does not appear to be any functional affect on implementing the class this way - so any argument would have to be from best practice or bad structure, rather than trying to prove that it doesn't work (because it does work - I'm just not sure it's appropriate). </p>
https://softwareengineering.stackexchange.com/q/3514965Shadhttps://softwareengineering.stackexchange.com/users/2762432017-06-24T01:05:30Z2017-06-24T20:13:49Z
<p>I am learning design patterns in Java and also working on a problem where I need to handle huge number of requests streaming into my program from a huge CSV file on the disk. Each CSV line is one request, and the first field in each line indicates the message type. There are 7 types of messages, each of which should be handled differently.</p>
<p>The code is something like the following: </p>
<pre><code>class Handler {
private CustomClass {….}
Map<String, CustomClass> map = new HashMap<String, CustomClass>();
Public void runFile() {
// Read the huge CSV file with millions of records, line by line
// for each line, get the string before the first comma (say X)
switch (X) {
case 1 : myMethod1(….); break;
case 2 : myMethod2(….); break;
case 3 : myMethod3(….); break;
// ...
default: // ...
}
}
// Methods 1, 2, 3 declarations
}
</code></pre>
<p>Note 1: Some of the methods affect the map and others don't.<br>
Note 2: Each request (method) uses different variables from the CSV line and executes a different logic.<br>
Note 3: requests/methods are NOT connected; i.e. <code>myMethod2()</code> does not logically follow <code>myMethod1()</code>.</p>
<p>Now my question – What is an appropriate design pattern for this problem? Is it fine if I keep the whole logic in one class (similar to the code above) without changing?</p>
https://softwareengineering.stackexchange.com/q/3468931Stevanhttps://softwareengineering.stackexchange.com/users/2691622017-04-10T07:57:09Z2017-04-10T19:34:24Z
<p>This is sort of a follow up question on <a href="https://softwareengineering.stackexchange.com/questions/160763/multiple-same-object-instantiation">Multiple Same Object Instantiation</a>.
And I think, is not really language specific, so this is applicable to Java and C#?</p>
<p>Version A</p>
<pre class="lang-java prettyprint-override"><code>public MyClass {
public void methodX() {}
public void methodY(int i, object o) {
GeometrySplitter splitter = new GeomterySplitter(int i, object o);
splitter.chop();
}
public void methodZ() {}
}
</code></pre>
<p>Version B</p>
<pre class="lang-java prettyprint-override"><code>public MyClass {
private GeometrySplitter splitter = new GeometrySplitter();
public void methodX() {}
public void methodY(int i, object o) {
splitter.chop(int i, object o);
}
public void methodZ() {}
}
</code></pre>
<p>A colleague says that Version B is a better code practice, because the class is only instantiated once. My own reasoning is that the internal variable is only used in <code>methodY(int i, object o)</code> and thus it should be created within the method itself, as displayed in Version A.</p>
<p>My colleague then reasons that if that method is called 4000 times a second. For every method call an new instance of that class is created. And this is bad for performance and memory use.</p>
<p>Is this true? If so or not, can someone clarify this?</p>
https://softwareengineering.stackexchange.com/q/1607638Lawrence Gimenezhttps://softwareengineering.stackexchange.com/users/617852012-08-14T05:35:54Z2017-01-03T18:38:02Z
<p>What exactly happens in Java when you instantiate the same object multiple times?</p>
<p>For example:</p>
<pre><code>Test test = new Test();
</code></pre>
<p>then later on I will call it again, <code>Test test = new Test();</code> again or inside a loop. Will the previous instantiation be disposed?</p>
https://softwareengineering.stackexchange.com/q/33593610Tripolahttps://softwareengineering.stackexchange.com/users/2528092016-11-13T11:51:40Z2016-11-15T00:59:09Z
<p>I'm new to object oriented programming and I don't understand what's the purpose of the main.</p>
<p>Yes, I read that it's the "entry point" of the program but what I don't understand is what should be in the main? And what are its responsibilities?</p>
<p>It may happen that something written in the main could be encapsulated in another object, but how much should you use this approach?</p>
<p>Here is my very first main I wrote in Java, it's very simple but it may make you understand my doubt better. I have an abstract class Animal which is extended by "Cat" and "Dog". I used the main to create some object and also as an "interface" with the user, indeed as you can see I used some conditional instruction to "ask the user" what he want to do.</p>
<p>My question arose from the fact that the interface could be encapsulated in another object and not giving that responsibility to the main.</p>
<pre><code> public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What type of animal do you want to create? \n dog cat");
String type = input.nextLine();
if ( Objects.equals(type, "dog")){
System.out.println("Enter the animal's age: ");
int age = input.nextInt(); // Scans the next token of the input as an int.
System.out.println("Enter the animal's name: ");
String name = input.next();
Dog first = new Dog(name, age);
}
else if ( Objects.equals(type, "cat")) {
System.out.println("Enter the animal's age: ");
int age = input.nextInt(); // Scans the next token of the input as an int.
System.out.println("Enter the animal's name: ");
String name = input.next();
Cat first = new Cat(name, age);
}
else{
System.out.println("Error: the specified type does not exist.");
}
System.out.println("The number of animals is:" + numberOfAnimals);
}
</code></pre>
https://softwareengineering.stackexchange.com/q/31749538Parashttps://softwareengineering.stackexchange.com/users/2050942016-05-04T07:14:00Z2016-05-05T19:12:38Z
<p>My current understanding of Inheritance implementation is that one should only extend a class if an <strong>IS-A</strong> relation is present. If the parent class can further have more specific child types with different functionality but will share common elements abstracted in the parent.</p>
<p>I'm questioning that understanding because of what my Java professor is recommending us to do. He has recommended that for a <code>JSwing</code> application we are building in class</p>
<p>One should extend all <code>JSwing</code> classes (<code>JFrame</code>,<code>JButton</code>,<code>JTextBox</code>,etc) into separate custom classes and specify GUI related customisation in them (like the component size, component label, etc)</p>
<p>So far so good, but he further goes on to advise that every JButton should have its own custom extended class even though the only distinguishing factor is their label.</p>
<p>For e.g. If the GUI has two buttons <strong>Okay</strong> and <strong>Cancel</strong>. He recommends they should be extended as below:</p>
<pre><code>class OkayButton extends JButton{
MainUI mui;
public OkayButton(MainUI mui) {
setSize(80,60);
setText("Okay");
this.mui = mui;
mui.add(this);
}
}
class CancelButton extends JButton{
MainUI mui;
public CancelButton(MainUI mui) {
setSize(80,60);
setText("Cancel");
this.mui = mui;
mui.add(this);
}
}
</code></pre>
<p>As you can see the only difference is in the <code>setText</code> function. </p>
<p>So is this standard practice? </p>
<p>Btw, the course where this was discussed is called <strong><em>Best Programming Practices in Java</em></strong></p>
<p><strong>[Reply from the Prof]</strong></p>
<p>So I discussed the problem with the professor and raised all the points mentioned in the answers.</p>
<p>His justification is that subclassing provides reusable code while following GUI design standards. For instance if the developer has used custom <code>Okay</code> and <code>Cancel</code> buttons in one Window, it will be easier to place the same buttons in other Windows as well.</p>
<p>I get the reason I suppose, but still it's just exploiting <em>inheritance</em> and making code fragile. </p>
<p>Later on, any developer could accidently call the <code>setText</code> on an <code>Okay</code> button and change it. The subclass just becomes nuisance in that case.</p>
https://softwareengineering.stackexchange.com/q/3140773AJJhttps://softwareengineering.stackexchange.com/users/2220212016-03-28T16:44:41Z2016-03-28T17:44:08Z
<p>I am wondering about best practices here.</p>
<p>MVC (Model - View - Controller) patterns involve separating components of your program that model the data, manipulate those models, and display those results to the user (usually through the UI) in some way.</p>
<p>What about a function that takes the model data and inserts it into a database? For example I have an object called a GameBoard, and I also want the ability to insert the state of this board into the SQL database for storage / historical purposes. I have a class that holds all my query functions.</p>
<p>But where would I call these functions from? Would this sort of functionality make the most sense to make it as a method of GameBoard? Or should it be part of the controller classes?</p>
<p>For example, I've got a GameBoard class and an SQLDatasource/SQLHelper class (which I call the "models"). The SQL classes have methods that take care of the queries and such. In Android, there are also Activity classes where all the "events" take place (I call these the "controllers"). The "view" takes place via code that binds the Activity to some XML. That being said, I normally instantiate the GameBoards in the Activity classes, and right now I also call the query functions from these same classes that accept a GameBoard as an argument.</p>
https://softwareengineering.stackexchange.com/q/18156759Daniel Kaplanhttps://softwareengineering.stackexchange.com/users/569452013-01-04T20:20:03Z2015-08-05T07:17:23Z
<p>Where I work I see lots of classes that do things like this:</p>
<pre><code>public class ClassThatCallsItsOwnGettersAndSetters {
private String field;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public void methodWithLogic() {
setField("value");
//do stuff
String localField = getField();
//do stuff with "localField"
}
}
</code></pre>
<p>If I wrote this from scratch, I would have written the <code>methodWithLogic()</code> like this instead:</p>
<pre><code>public class ClassThatUsesItsOwnFields {
private String field;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public void methodWithLogic() {
field = "value";
//do stuff
//do stuff with "field"
}
}
</code></pre>
<p>I feel that when the class calls its own getters and setters, it makes the code harder to read. To me it almost <em>implies</em> that complex logic is happening in that method call even though in our case it almost never is. When I'm debugging some unfamiliar code, who's to say that the bug isn't some side effect in that method? In other words, it makes me take lots of side trips on the journey of understanding the code. </p>
<p>Are there benefits to the first method? Is the first method actually better?</p>
https://softwareengineering.stackexchange.com/q/11193856Ilianhttps://softwareengineering.stackexchange.com/users/378532011-10-02T13:40:32Z2014-06-05T05:13:05Z
<p>This question is subjective but I was just curious how most programmers approach this. The sample below is in pseudo-C# but this should apply to Java, C++, and other OOP languages as well.</p>
<p>Anyway, when writing helper methods in my classes, I tend to declare them as static and just pass the fields if the helper method needs them. For example, given the code below, I prefer to use <strong>Method Call #2</strong>.</p>
<pre><code>class Foo
{
Bar _bar;
public void DoSomethingWithBar()
{
// Method Call #1.
DoSomethingWithBarImpl();
// Method Call #2.
DoSomethingWithBarImpl(_bar);
}
private void DoSomethingWithBarImpl()
{
_bar.DoSomething();
}
private static void DoSomethingWithBarImpl(Bar bar)
{
bar.DoSomething();
}
}
</code></pre>
<p>My reason for doing this is that it makes it clear (to my eyes at least) that the helper method has a possible side-effect on other objects - even without reading its implementation. I find that I can quickly grok methods that use this practice and thus help me in debugging things.</p>
<p>Which do you <em>prefer</em> to do in your own code and what are your reasons for doing so?</p>
https://softwareengineering.stackexchange.com/q/2075563sinθhttps://softwareengineering.stackexchange.com/users/626832013-08-07T17:33:27Z2013-12-06T06:46:08Z
<p>About a third of my code is wrapped inside a Facade class. Note that this isn't a "God" class, but actually represents a single thing (called a <code>Line</code>). Naturally, it delegates responsibilities to the subsystem behind it.</p>
<p>What ends up happening is that two of the subsystem classes (<code>Output</code> and <code>Timeline</code>) have all of their methods duplicated in the <code>Line</code> class, which effectively makes <code>Line</code> both an <code>Output</code> and a <code>Timeline</code>. It seems to make sense to make <code>Output</code> and <code>Timeline</code> interfaces, so that the <code>Line</code> class can implement them both. At the same time, I'm worried about creating parallel class and interface structures.</p>
<p>You see, there are different types of lines <code>AudioLine</code>, <code>VideoLine</code>, which all use the same type of <code>Timeline</code>, but different types of <code>Output</code> (<code>AudioOutput</code> and <code>VideoOutput</code>, respectively). So that would mean that I'd have to create an <code>AudioOutputInterface</code> and <code>VideoOutputInterface</code> as well. So not only would I have to have parallel class hierarchy, but there would be a parallel interface hierarchy as well. </p>
<p>Is there any solution to this design flaw?</p>
<p>Here's an image of the basic structure (minus the Timeline class, though know that each Line has-a Timeline):</p>
<p><img src="https://i.sstatic.net/JEwCv.png" alt="enter image description here"></p>
<p>NOTE: I just realized that the word 'line' in <code>Timeline</code> might make is sound like is does a similar function as the <code>Line</code> class. They don't, just to clarify. </p>
https://softwareengineering.stackexchange.com/q/2087910Haseeb Akhtarhttps://softwareengineering.stackexchange.com/users/977742013-08-19T11:01:26Z2013-08-19T11:53:36Z
<p>I've made a file browser in java that opens and read already been made excel files. (using Apache poi 3.9 library)
program read those files perfectly but i want to update some of those files. how can i be able to update those files through my program.
is there is any library or function/class that might be helpful, or also any other language that can support that feature (among c/c++, python)..???</p>
https://softwareengineering.stackexchange.com/q/1993561sinθhttps://softwareengineering.stackexchange.com/users/626832013-05-24T20:51:50Z2013-05-25T01:38:34Z
<p>This might seem like an odd question, but I'm worried that I'm putting too many things as constants/finals at the top of my java class. I've started to put every value that is in my program into a constant (At least the ones that influence it's overall effect). The reason I'm doing it is because then it's easy to find the values and change them latter, even if they are only used once, it's easier to find them at the top. Is this a bad or good practice, I really have no idea. </p>
<p>Here's an example:</p>
<pre><code>private static final Color COLOR_SELECTED = Color.BLUE;
private static final Color COLOR_ALTERNATE_ONE = Color.WHITE;
private static final Color COLOR_ALTERNATE_TWO = new Color(240, 240 , 240);
private static final Color TEXT_COLOR = Color.black;
</code></pre>