Avatar billede fredand Forsker
28. februar 2022 - 11:02 Der er 2 kommentarer og
1 løsning

Is there any point of making a get-method private?

Hello,
Is it really a good practice to incapsulate "mob" and its getter like this if you look at the following code:

@Stateless
public class MyBean
{
@EJB
private MyOtherBean mob;

public boolean doStuff(int i)
{
getMob().doSome();
If( i < 10) { return true;}
return false;
}

private MyOtherBean getMob()
{
return mob;
}
}

I noticed this while I was writing a test for doStuff() and I needed to mock dependencis and run into a problem to mock away "mob". If the getMob() was protected "package" I easily could mock it.
What could be the reason for make the getMob() private? (Inside the get-method there is neither or nor checks like some other conditions either)


Best regards Fredrik
Avatar billede arne_v Ekspert
28. februar 2022 - 14:50 #1
I don't see a point in doing it. And I would not have done it,

Sure - one day you may want to do something when mob is accessed, but when that happens then you will need to edit this file anyway and can add the getter at that time. And because it is private then there will be no impact on anything else.

KISS and YAGNI,

But for some it has become a sort of religious principle never to access fields directly.
Avatar billede arne_v Ekspert
28. februar 2022 - 16:00 #2
If you decide to keep that method then make it package visible to at least get some benefits from it.
Avatar billede fredand Forsker
28. februar 2022 - 20:31 #3
Thank you for that input amigo!
Best regards
/Fredrik
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester